Home > Software design >  Vuetify - Show tooltip on click
Vuetify - Show tooltip on click

Time:04-10

enter image description here

I have button that trigger a tooltip when my user clicked Copy

<v-btn @click="showCopiedText = !showCopiedText; copyHtmlText()">Copy</v-btn>

<v-tooltip v-model="showCopiedText" right>
    <span>Copied!</span>
</v-tooltip>

It works but my tool tip kept showing the tip left of my windows instead of next to my button.

enter image description here

CodePudding user response:

The v-btn should be inside the v-tooltip's activator slot, so that the component can position itself around the contents:

  1. Move the v-btn into the v-tooltip's activator slot.

  2. In the v-btn's click-handler, use the slot's on property to simulate a mouseenter to show the tooltip; and mouseleave after a timeout to hide it. Make sure to clear the timeout in beforeDestroy in case the component is unmounted before the timeout.

<v-tooltip bottom>
  <template v-slot:activator="{ on, attrs }">
    1️⃣
    <v-btn v-bind="attrs" @click="toClick(on, $event)">Copy</v-btn>
  </template>
  <span>Copied</span>
</v-tooltip>
export default {
  beforeDestroy() {
    clearTimeout(this._timerId)
  },
  methods: {
    2️⃣
    toClick({ mouseenter, mouseleave }, e) {
      clearTimeout(this._timerId)
      mouseenter(e)
      this._timerId = setTimeout(() => mouseleave(e), 1000)
    }
  }
}

demo 1

Alternatively, you can use a v-model on the v-tooltip to show/hide the tooltip instead of the mouseenter/mouseleave simulations:

  1. Declare a show Boolean prop, and use the prop as the v-tooltip's v-model.

  2. In the v-btn's click-handler, set the prop to true, and use a timeout to reset it to false. Make sure to clear the timeout in beforeDestroy in case the component is unmounted before the timeout.

<v-tooltip bottom v-model="show"> 1️⃣
  <template v-slot:activator="{ attrs }">
    <v-btn v-bind="attrs" @click="showTooltip">Copy</v-btn>
  </template>
  <span>Copied</span>
</v-tooltip>
export default {
  data() {
    return {
      show: false, 1️⃣
    }
  },
  beforeDestroy() {
    clearTimeout(this._timerId)
  },
  methods: {
    showTooltip() {
      2️⃣
      this.show = true;
      this._timerId = setTimeout(() => this.show = false, 1000)
    }
  }
}

demo 2

CodePudding user response:

From VueJS docs a tooltip still needs to be positioned. In this example the tooltip is inside a vueJS grid and is positioned correctly. Hopefully it helps.

  • Related