1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Vuetify3】Tooltipで表示される値を可変にしたい

Posted at

はじめに

Vuetify3にはTooltipという、ボタンにHoverすると設定しておいた情報を表示する機能があります1

                                           
tooltip1.gif
左のボタンにHoverすると右の黒いボタン部分が表示される

可変の値を表示するのに少し苦戦したので、記録しておきます。

公式サイトのサンプルコード

まず、上の動画のように指定した文言を単純に表示したい場合、公式サイトにあるサンプルコードで問題なく動作します。

<v-tooltip text="Tooltip">""内に表示したい文字列を入れるだけです。

<template>
  <v-app>
    <v-container>
      <v-tooltip text="Tooltip">
        <template v-slot:activator="{ props }">
          <v-btn v-bind="props">HOVER OVER ME</v-btn>
        </template>
      </v-tooltip>
    </v-container>
  </v-app>
</template>

可変な値を表示するサンプルコード

では、表示したいのが可変の値の場合はどうするか。

例として、0~9の値をランダムに生成して返す関数の返り値を表示します。

function getRandomInt(max) {
    return Math.floor(Math.random() * max)
}

素直に考えるとtext="{{ getRandomInt(10) }}"で動作しそうですが、、それでは駄目でした。

                                          
スクリーンショット 2024-03-01 21.16.26.png
二重括弧と関数名がそのまま表示されてしまう

<template>の下に<span>タグを設置し、そこに指定すると上手く行きました!

<script setup>
function getRandomInt(max) {
    return Math.floor(Math.random() * max)
}
</script>

<template>
  <v-app>
    <v-container>
      <v-tooltip>
        <template v-slot:activator="{ props }">
          <v-btn v-bind="props">HOVER OVER ME</v-btn>
        </template>
        <!-- この下に指定 -->
        <span>{{ getRandomInt(10) }}</span>
      </v-tooltip>
    </v-container>
  </v-app>
</template>

Hoverするたびに関数が実行され、ランダムな値を表示できます。

                                   
スクリーンショット 2024-03-01 21.26.10.png スクリーンショット 2024-03-01 21.26.20.png

終わりに

中盤に書いたtext="{{ getRandomInt(10) }}"で上手くいかなかったので色々試していたところ、公式サイトのVisibilityのサンプルコードで<span>タグに文字列を書くやり方をしていたので、真似したらたまたま上手く行きました。

もうちょっと親切に例を書いておいてくれればいいのに、、と思ったので記録しておきます。

  1. Tooltipを表示する位置は上下左右どこでも指定できます。詳しくは公式サイトをどうぞ。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?