Differences between Vue.js onMounted and watching refsVue.js offers

When it comes to calling a function that requires an HTMLElement as an argument, the element in question is rendered within my page template and therefore I need to ensure it is actually in the DOM before making the call. Two potential methods for waiting for the element to be visible are:

  1. Utilizing a ref
<template><div ref="el"></div></template>
<script>
import {ref, watch} from "vue";
import {exampleFunction} from "example";
export default {
    setup() {
        const el = ref();
        watch(el, (newEl, oldEl) => {
            if (typeof oldEl === "undefined") // Ensure function is called only once
                exampleFunction(newEl);
        });
        return {el}
    }
}
</script>
  1. Using onMounted
<template><div id="el" ref="el1"></div></template>
<script>
import {onMounted, ref} from "vue";
import {exampleFunction} from "example";
export default {
    setup() {
        const el1 = ref();
        onMounted(() => {
            let el2 = document.querySelector("#el"); 
            exampleFunction(el2);
            // OR exampleFunction(el1.value);
        });
        return {el1}
    }
}
</script>

In my understanding, both of these approaches provide a reference to the element once it is present in the DOM. Is there any particular reason why one method might be preferred over the other? Are there any nuances about either of these scenarios that I may have overlooked? Lastly, could there be another solution entirely that would be more suitable for this situation?

Answer №1

In the given scenario, both options yield the same result. You can opt to utilize onMounted with a ref instead of using document.querySelector.

Personally, I lean towards leveraging watch or watchEffect when waiting for specific states to be achieved. The use of onMounted is limited in cases where conditional rendering like v-if is involved.

In terms of performance, there isn't much disparity between the two methods. While watch is available, the ref typically only changes once throughout its lifecycle. If by chance the reference does change, onMounted will not function as expected.

Answer №2

Revamp your code to resemble the following:

<template>
  <div id="el"></div>
</template>

<script>
export default {
  mounted() {
    let el = document.querySelector("#el");

    exampleFunction(el);

    return {el}
    }
}
</script>

Don't forget to refer to the Vue Life Cycle Hooks documentation for further insights.

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

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...

What is the process for integrating Android Java code with Node.js code?

I have some code that I am trying to integrate with Node.js for Firebase notifications on my Android application. I found a blog post outlining the implementation here: The Node.js code listens to changes in my Firebase Database and triggers notifications ...

A convenient way to implement a polyfill for the Object.create method in JavaScript using

A new way to implement the polyfill for javascript Object.create() has left me puzzled. You can find the code here. if (typeof Object.create != 'function') { // Implementation steps based on ECMA-262, Edition 5, 15.2.3.5 // Reference: ...

Enhancing a class's properties from its parent component using React

Recently, I decided to dive into React by taking on the challenge of rebuilding the Google Weather app. My main objective is to have the main section update whenever a day is selected. Initially, I believed that updating the props within handleSelectionAt( ...

How can I implement a hover-over image change effect similar to the one seen in Gmail accounts?

I am attempting to implement a feature that allows users to change their image, similar to what can be done in a GMail account. When the user hovers over the image, an option to "change image" should appear. This may be a new concept for me because I am ...

The feature for sending posts in Angular.js appears to be malfunctioning

I have developed a rest-API for adding todos in a MongoDB database. When I use Postman with the setup below, I can successfully save instances: http://localhost:3000/api/addtodo x-www-form-urlencoded with values text="Test", completed: "false". However, ...

Encountering net::ERR_CONNECTION_RESET and experiencing issues with fetching data when attempting to send a post request

I am facing a React.js task that involves sending a POST request to the server. I need to trigger this POST request when a user clicks on the submit button. However, I keep encountering two specific errors: App.js:19 POST http://localhost:3001/ net::ERR_CO ...

Submitting forms with Ajax without reloading the page can cause errors in Internet Explorer

Simply put: Upon clicking the login button in Firefox, Chrome, or Safari, the form is submitted correctly, running a validation via ajax and opening a new page. However, in Internet Explorer (version less than 9), the submission attempts to post to the c ...

When working on a React/Redux application, how do you decide between explicitly passing down a prop or retrieving it from the global state using mapStateToProps?

As I embark on creating my inaugural React-Redux application, a recurring decision I face is whether to employ <PaginationBox perPage={perPage} /> or opt for <PaginationBox /> and then implement the following logic: function mapStateToProps({p ...

How can I work with numerous "Set-Cookie" fields in NextJS-getServerSideProps?

When working with getServerSideProps, I found a way to set multiple cookies on the client device. This is the code snippet that I used: https://i.stack.imgur.com/Kbv70.png ...

Use Material UI Grid to create a horizontal line design instead of focusing on making the

Is there a way to turn off responsiveness for the material UI grid similar to how it can be done with a basic HTML table? While an HTML table scales down and adds a horizontal scroll bar, the material UI grid remains responsive as shown in the example belo ...

Update the button functionality according to the button's unique identifier

I am trying to dynamically change the button's redirect link based on its ID in my NEXT.JS project, but as a newcomer to this framework, I am unsure of how to accomplish it. I understand that this modification should be done after rendering, possibly ...

Is it possible to trim a video using HTML code?

I am trying to find a way to crop a video using HTML 5. <video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video> Currently, the video has a resolution of 640x360. However ...

``Are you looking to create multiple canvases in a loop?

I've managed to get this command working exactly as I wanted: http://jsfiddle.net/m1erickson/64BHx/ However, I didn't anticipate how challenging it would be to turn the drawing into reality here: What I attempted to do is illustrated in this li ...

What steps should I take to solve this wheel-related issue in my Vue 3 application?

I have been developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I am tackling the implementation of a search feature and I've encountered a bug. The "search-box" component is located in src&b ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Create a personalized form with HTML and JQuery

Currently, the data is displayed on a page in the following format: AB123 | LHRLAX | J9 I7 C9 D9 A6 | -0655 0910 -------------------------------------------------------- CF1153 | LHRLAX | I7 J7 Z9 T9 V7 | -0910 1305 ---------------- ...

What is the process for creating a global variable in JavaScript?

Having trouble changing the value of "invocation_num" within a loop? I attempted to modify it as follows, but ended up with an undefined value. Any help would be greatly appreciated. $(document).on("click", '.favoret', function(){ document ...

Steps for including a font ttf file in Next.js

As a newcomer to Nextjs, I am eager to incorporate my own custom fonts into my project. However, I find myself completely bewildered on how to execute this task (my fonts can be found in the "public/fonts/" directory). The contents of my global.css file ar ...

When importing modules in node.js, the presence of a function can overwrite another function even if it

Within this code snippet, I am utilizing Express.js. //index.js app.use('/',routes()); //app/routes.js module.exports = function() { express = require('express'); const loggedUserProfileController = require('../controller ...