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

The JavaScript program for the shopping list is experiencing issues with the formatting of list items

I have been working on developing a shopping list program using JavaScript. The program includes an input box and an "add item" button, which adds the text entered in the input field to an unordered list as a list item. Each list item also contains an imag ...

Receiving an unanticipated value from an array

Actions speak louder than words; I prefer to demonstrate with code: //global variable var siblings = []; var rand = new Date().getTime(); siblings.push('uin_' + rand); alert(siblings['uin_' + rand]); // undefined Why is it coming up ...

Switch between showing and hiding a div by clicking on the panel header and changing the symbol from + to

I need assistance with a panel feature on my website. The panel should expand when the "+" symbol is clicked, displaying the panel body, and the "+" symbol should change to "-" indicating it can be collapsed by clicking it again. There is a slight twist t ...

Utilizing Vue.js to set the instance global property as the default value for a component prop

Is it possible to access a global property from my vue instance when setting a default prop value in my component? This is what I would like to achieve props: { id: { type: String, default: this.$utils.uuid } } I attempted to use an arrow fun ...

Passing the index in React Native

I am currently developing a music app utilizing the react-native-track-player library. I have created three components named Clusters, Songlist, and Play. Understanding How the Screen Works The flow of components is as follows: Clusters component -> S ...

What factors influence the speed of an Ajax request?

It is common knowledge that the amount of data transmitted to the server, as well as the volume of information returned in a call can greatly affect its speed. However, what I am curious about is whether the following factors might also impact the transmi ...

EJS Templates with Node.js: Embracing Dynamic Design

Is there a way to dynamically include templates in EJS without knowing the exact file name until runtime? The current EJS includes only allow for specifying the exact template name. Scenario: I have an article layout and the actual article content is stor ...

Filtering an RXJS BehaviorSubject: A step-by-step guide

Looking to apply filtering on data using a BehaviorSubject but encountering some issues: public accounts: BehaviorSubject<any> = new BehaviorSubject(this.list); this.accounts.pipe(filter((poiData: any) => { console.log(poiData) } ...

A guide on efficiently incorporating a php variable into json format, then transferring it to ajax

My Sample Code var ajaxResponse = xmlhttp.responseText; //ajax response from my php file jsonData = JSON.parse(ajaxResponse); alert(jsonData.result); And in my PHP Script $resultValue = 'Hello'; echo '{ "result":"' . $result ...

Guide on placing stickers on an item in Three JS

Recently, I began experimenting with the three.js library and have a question about decals: I managed to create a sphere with a texture applied to it. Is there a way to overlay another texture on specific areas of the sphere without repeating the original ...

What is the method to display a group label using ng-table?

Does anyone have experience creating a group in ng-table? <div> <div ng-controller="ContractsController" style="position: relative;background:whitesmoke; border:1px solid lightgray; border-radius:5px; margin-top:0px; margin-bottom:5px; h ...

Struggling to get your HTML to Express app Ajax post request up and running?

I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed usi ...

Checking for an empty value with javascript: A step-by-step guide

Below is an HTML code snippet for checking for empty or null values in a text field: function myFormValidation() { alert("Hello"); var name = document.getElementById("name").value; alert(name); if (name == null || name == "") { document.ge ...

Update the js file by incorporating the import statement

Currently, I am in the process of transitioning to using imports instead of requires for modules. Here is an example of my previous code: const { NETWORK } = require(`${basePath}/constants/network.js`); The content of network.js file is as follows: export ...

Laravel and Vue: Retrieve complex data with multiple relationships

In my data model, I have a concept of Exercise which is linked to Topic, and Topic is associated with Subject. By using the code snippet below: Exercise::with('topic')->get() I can easily access the properties of the current topic within Vu ...

Tips for enabling the OnLoad Event for a React Widget

Hey there! I'm a beginner with React and I'm struggling to call a function once after the component is created. I tried adding an onLoad event in the component creation, but it's not working as expected. The function 'handleClick' ...

Is there a way to calculate the total of three input values and display it within a span using either JavaScript or jQuery?

I have a unique challenge where I need to only deal with positive values as input. var input = $('[name="1"],[name="2"],[name="3"]'), input1 = $('[name="1"]'), input2 = $('[name="2"]'), input3 = $('[name=" ...

Modify x and y axes in highcharts for stacked columns

Can anyone assist me in finding charts similar to the one shown below? I am interested in utilizing the stacked column charts provided by the highcharts library. However, I need to modify the presentation of the data values as demonstrated in the image. I ...

Restricting the fields in a $lookup operation in MongoDB

My Mongo object follows the schema provided below. { "_id" : "59fffda313d02500116e83bf::5a059c67f3ff3b001105c509", "quizzes" : [ { "topics" : [ ObjectId("5a05a1e1fc698f00118470e2") ], " ...

Is it possible to customize the appearance of the selected item in a select box? Can the selected value be displayed differently from the other options?

My current project involves working with the antd' select box. I have been trying to customize the content inside the Option which usually contains regular text by incorporating some JSX into it. The output currently looks like this: I have also crea ...