Is there a way to attach a mouseover event to a Vue ref element in Javascript?

I want to remove the mouseOver event from the template using $ref and control the mouseOver behavior within javascript. The Components component contains a child component called myStats, which should only be displayed when hovering over Components.

  1. I need help figuring out how to use ref to replace the commented-out template code.
  2. Should I utilize a function of myStats (like onMouseEvent) or can I handle mouseOver solely inside Components?

Components code:

<template>
  <div class="pv-lookup" ref="myStats">
    <!-- I would like to get rid of the commented out mouse hover event code below by using $ref: -->
    <!-- <div @mouseover="mouseOver = true" @mouseout="mouseOver = false"> -->
    <div>
      <someComponent1 />
      <someComponent2 />
      <myStats v-if="mouseOver" @mouseMoved="onMouseMoved"/>
    </div>
  </div>
</template>

<script>
export default class Components extends Vue {
  public mouseOver = false;

  @Emit()
  public onMouseMoved() {
    this.mouseOver = !this.mouseOver;
  }

  mounted() {
    this.$nextTick(() => {
      if (this.isInhouseClient || this.isInhouse) {
        // TODO: set value for this.mouseOver

        // Approach 1:
        // ERROR: Property 'onMouseEvent' does not exist on type 'Vue | Element | Vue[] | Element[]'.
        this.$refs.myStats.onMouseEvent();

        // Approach 2:
        // ERROR: Property 'onMouseEvent' does not exist on type 'MouseEvent'. Did you mean 'initMouseEvent'?
        const myStats= this.$refs.myStatsas HTMLElement;
        myStats.addEventListener("mouseover", function( event ) {
          event.onMouseEvent();
        }, false);
        
        // Approach 3:
        // It's the simplest, but how do I connect with 'ref'?
        this.mouseOver = !this.mouseOver;
      }
    });
  }
}
</script>

myStats code:

<script>
export default class myStats extends Vue {
  public mouseOver: boolean = false;

  @Emit()
  public mouseMoved(){}
  
  public onMouseEvent() {
    this.mouseMoved();
  }
}
</script>

Thank you for your insights

Answer №1

To incorporate event listeners for the mouseover and mouseout events on the DOM element, you can simply attach them. It is important to note that these events propagate from child elements as well. In this scenario, it might be more suitable to utilize mouseenter and mouseleave.

Your revised code would look like this:

  mounted() {
    const myStatsEl = this.$refs.myStats; // obtain the DOM element of the Components component
    myStatsEl.addEventListener("mouseenter", (event) => {
      this.mouseOver = true;
    });

    myStatsEl.addEventListener("mouseleave", (event) => {
      this.mouseOver = false;
    });
  },

You do not need to dispatch events from the myStats component or invoke its methods.

Having said that, the recommended 'Vue-way' approach would involve using @mouseenter and @mouseleave, which offers a cleaner solution. It is unclear why one would choose not to use that method. I cannot envision any scenarios where this alternative could prove restrictive.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to store a randomly generated variable in JavaScript for future reference?

Currently, I am involved in a project that involves generating random variables to create unique scenes. One specific variable is the location of these scenes. My goal is to be able to generate a location with just one button click. Subsequently, by pressi ...

Having trouble with Vue router functionality

I've attempted troubleshooting my router countless times, but it still won't work properly. I'm unable to navigate or switch to different pages in my Vue project. Despite following all the steps outlined in this link , nothing seems to chang ...

Converting a Finsweet hack #4 from jQuery to pure JavaScript in Webflow: Step-by-step guide

I have a jQuery code that I need to convert to pure JavaScript. Can you assist me in translating this code into pure JavaScript? I have left comments in the code to make it easier. ORIGINAL JQUERY CODE: // When the DOM is ready document.addEventListener(& ...

Node.js: Capturing requests and responses for console logging

I'm currently working on a Hapi server using Good to log all requests and responses to the console. I've been able to successfully log responses but I'm facing issues with logging the body of the response, and for requests, I'm not gett ...

When utilizing Vuex state within a computed property to trigger the opening of a modal, any modifications are neglected, resulting in the

Within my codebase, I have implemented a dynamic method for adding modal states to the Vuex store and activating them throughout the application. Despite successfully changing the state, I encountered an issue where clicking a button that dispatches the to ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...

The $scope.$watch function is not triggering events within a controller of a ui.bootstrap.modal

Currently, I am utilizing UI bootstrap for Angular and have successfully integrated the ui.bootstrap.modal component into my project. Everything seems to be working smoothly except for one issue I am encountering. Despite setting up a $scope.$watch to trac ...

Show live data in JQgrid on Codeigniter platform

I'm currently working on a project using CodeIgniter that involves implementing a JQgrid table to display data. While I am able to retrieve the data from the database, I have encountered difficulties in displaying it within the JQgrid itself. However, ...

The search functionality is malfunctioning within the JavaScript table

I am working with a table that I want to filter based on input values. However, the current filtering function is not working as expected. I have utilized an onkeyup function for the filtering process. For more details and a live example, check out the jsf ...

Using Angular 2: Exploring the power of observables for broadcasting events during a forEach loop

Upon testing the service within a forEach loop, I noticed that the parameter I passed to the service ended up being the last one in the iteration. I initially suspected that the issue was due to closures, so I attempted using an anonymous function to add ...

The pie chart fails to fully display

Check out the repro example I made here. The legend is displaying properly, but the graph is not showing up. What could be causing this unexpected issue? ...

What could be causing the malfunction in the cloning of the carousel item?

My goal was to create a carousel that displays multiple images in one slide. However, I encountered an issue where once the fourth image is reached, the other three images are forcibly hidden. I want to give credit to the original creator of this code snip ...

Can Mutation Observer be utilized in conjunction with a Three.js element in an A-Frame environment?

export class ColliderComponent { constructor() { this.observer = this.createMutationObserver(); this.registerAframeComponent(); } //Registers the AFRAME component. registerAframeComponent(){ const self = this; AFRAME.regi ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

Retrieving information from a separate JavaScript file

I'm currently developing a Discord Bot and my code is all contained within one file. My goal now is to break this code up into multiple files for better organization. For instance, I plan to have: index.js which will handle all the requires (e.g. var ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...

Utilize computed properties in place of v-if within a v-for loop

I created a page that showcases the birthdays organized by each team's respective month. The design incorporates two buttons which enable users to navigate between months seamlessly. Initially, I utilized v-if for this purpose and it worked effective ...

What is the method to determine the index of a removed element within a subarray?

In my array, all = [2,3,4,12, 55,33], there is a sub-array named ar1 = [12, 55, 33] starting from the value 12. If I remove a value from all that is present in ar1 (e.g. 12), how can I determine the index of this value in ar1 (0 for 12) so I can also remo ...

Creating and inserting multiple objects into a table in Sails JS while bypassing any existing rows

Is there a way to insert an array of objects into a table while avoiding duplicate rows? I have a model defined as follows: //Test.js module.exports={ tableName:'test', connection: 'mysqlServer', attributes:{ id:{ type: ...

What is the best way for me to incorporate images retrieved from an API call into my

Hey everyone, this is my first time posting on here so if there's anything I'm missing, please let me know! I've run into an issue with the images on my categories page not aligning properly and being different sizes after I incorporated som ...