SoFunction
Updated on 2025-04-05

Two implementation methods for vue to obtain DOM elements and set properties

Here I have thought of two methods:

Method 1:

Directly add id to the corresponding element, then ("id"); get it, and then set the corresponding attribute or style

Method 2:

Use ref, add ref="name" to the corresponding element and then this.$ to get the element

Note: Before obtaining the corresponding element, it must be mounted on the mount hook, otherwise the obtained value will be empty.

If you add an id to a child component and modify a custom attribute, it will directly load the outer div corresponding to the child component, and will not change the value of the original custom attribute of the child component.

If you add a ref to the child component, then get the DOM element and change the value of the corresponding custom attribute, vue will report an error:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "title"

The two implementation methods of obtaining DOM elements and setting attributes in the above article vue are all the content shared by the editor. I hope it can give you a reference and I hope you can support me more.