Home >Web Front-end >Vue.js >How to get dom elements in vue
In Vue, methods to obtain DOM elements include: 1. Use $refs to access elements with ref attributes; 2. Use the # modifier in the template to directly bind elements to $refs; 3. Access The $el attribute of the child component; 4. Use the "Components" panel of Vue Devtools.
Methods to get DOM elements in Vue
In Vue, you can get DOM elements through the following methods :
1. The $refs
$refs
attribute is an object that contains all items with ref## in the template. # Reference to the attribute's element. Use
$refs to directly access DOM elements, as shown below:
<code class="vue"><template> <div ref="myElement"></div> </template> <script> export default { mounted() { console.log(this.$refs.myElement); // 输出 DOM 元素 } } </script></code>
2. Use in the template Modifiers **
# Modifiers can bind elements in the template directly to the
$refs object of the component instance, as shown below:
<code class="vue"><template> <div #myElement></div> </template> <script> export default { mounted() { console.log(this.$refs.myElement); // 输出 DOM 元素 } } </script></code>
3. To access the root DOM element of the child component
, you can use$children to access the child component, and then you can use
$el Property gets the root DOM element of the child component, as shown below:
<code class="vue"><template> <ChildComponent ref="child"></ChildComponent> </template> <script> export default { mounted() { console.log(this.$refs.child.$el); // 输出子组件的根 DOM 元素 } } </script></code>
4. Using Vue Devtools
Vue Devtools is a browser extension that can be used to inspect Vue app. In Devtools, you can directly access DOM elements through the "Components" panel, as shown below:The above is the detailed content of How to get dom elements in vue. For more information, please follow other related articles on the PHP Chinese website!