Usage: 1. "$refs" is used to register reference information for elements or subcomponents, the syntax is "this.$refs.(ref value)" or "this.$refs.(ref value).method () "; 2. "$el" is used to obtain the DOM element associated with the Vue instance, the syntax is "this.$refs.component".
The operating environment of this article: Windows 10 system, Vue version 2.9.6, DELL G3 computer.
ref is used to register reference information for elements or sub-components
ref There are three types Usage:
1. Add ref to an ordinary element, use this.$refs. (ref value) to get the dom element
2. Add ref to a subcomponent, use this.$refs. (ref value) What is obtained is the component instance, and all methods of the component can be used. When using the method, you can use it directly this.$refs.(ref value).method().
3. How to use v-for and ref to obtain a set of arrays or dom nodes
If you want to add different refs through v-for traversal, remember to add the : sign, that is: ref = something Variable;
This is the same as other attributes. If it is a fixed value, there is no need to add the : sign. If it is a variable, remember to add the : sign. (If a colon is added, it means that what follows is a variable or expression; if there is no colon, it means the corresponding string constant (String)
The pitfalls that should be noted are:
1, ref It needs to be available after the DOM rendering is completed. When using it, make sure that the DOM has been rendered. For example, call it in the life cycle mounted(){} hook, or call it in this.$nextTick(()=>{}) .
2. If ref is looped out and has multiple duplicate names, then the value of ref will be an array. At this time, to get a single ref, you only need to loop.
vm.$el
Get the DOM element associated with the Vue instance;
For example, I want to get the custom component tabControl and get its OffsetTop. Just You need to get the component first.
Set the attribute ref='a name (tabControl2)' in the component,
Then this.$refs.tabControl2 will get the component
Remember: ref attribute, when getting the component, you need to use $refs
to get OffsetTop. The component is not a DOM element, there is no OffsetTop, and it cannot be obtained by clicking .OffsetTop. You need to get it through $el DOM elements in components
[Related recommendations: "vue.js tutorial"]
The above is the detailed content of What is the usage of $refs and $el in vue. For more information, please follow other related articles on the PHP Chinese website!