search

Home  >  Q&A  >  body text

How to set non-responsive data for component instances in Vue 3?

<p>There is a similar problem for Vue2, it is recommended to use <code>$options</code>. </p> <p>But it doesn't seem to work for Vue 3. </p> <p>First of all, the Vue 3 documentation says that <code>$options</code> is read-only. </p> <p>So when I try to initialize the tooltip in the instance when the component is mounted, I get very strange behavior, when the tooltips are displayed, they are displayed from the last created component, so it seems that<code> ;$options</code>is "global" in some way? </p> <p>When putting <code>tooltip</code> inside <code>data</code> everything works fine, but obviously the tooltip is not supposed to be responsive and I want to put it inside < outside code>data</code>. </p> <pre class="brush:html;toolbar:false;"><template> <i :class="['bi ', icon, hover && 'text-primary']" class="bg-body" @mouseover="hover = true; $options.tooltip.show();" @mouseleave="hover = false; $options.tooltip.hide();" @click="$options.tooltip.hide();" style="cursor: pointer" :title="title" ref="icon" /> </template> <script> import {Tooltip} from "bootstrap"; export default { props: ["icon", "title"], tooltip: null, data() { return { hover: false } }, mounted() { this.$options.tooltip = new Tooltip(this.$refs.icon,{ placement: 'bottom', trigger: 'manual', title: this.title || '' }); }, } </script> </pre></p>
P粉973899567P粉973899567451 days ago561

reply all(1)I'll reply

  • P粉404539732

    P粉4045397322023-08-26 14:57:42

    You can attach non-responsive properties to component instances directly in the mounted() hook:

    <script>
    export default {
      // tooltip: null,
      mounted() {
        // this.$options.tooltip = new Tooltip(...)
        this.tooltip = new Tooltip(...)
      },
    }
    </script>
    
    <template>
      <!-- BEFORE -->
      <i
          @mouseover="hover = true; $options.tooltip.show();"
          @mouseleave="hover = false; $options.tooltip.hide();"
          @click="$options.tooltip.hide();"
          ref="icon"
      />
    
      <!-- AFTER -->
      <i
          @mouseover="hover = true; tooltip.show();"
          @mouseleave="hover = false; tooltip.hide();"
          @click="tooltip.hide();"
          ref="icon"
      />
    </template>
    

    Demo

    reply
    0
  • Cancelreply