Home >Web Front-end >Vue.js >How to get dom elements in vue
In Vue, there are three ways to obtain DOM elements: 1. Use the ref attribute to specify a reference variable for the element and access it through this.$refs; 2. Directly use the root element of the component this.$el; 3. . Use the querySelector method to query on bound elements.
Get DOM elements in Vue
In Vue applications, you can get DOM elements through the following methods:
1. ref attribute
ref
attribute to a component or element and specify a reference variable name. this.$refs
object to access elements with the ref
attribute. <code class="vue"><template> <div ref="myDiv"></div> </template> <script> import { ref } from 'vue' export default { setup() { const myDiv = ref(null) // 声明一个空引用变量 return { myDiv } }, mounted() { console.log(this.$refs.myDiv) // myDiv 元素 } } </script></code>
2. $el attribute
$el
The attribute points to the root element of the current component. <code class="vue"><template> <div></div> </template> <script> import { ref } from 'vue' export default { setup() { const myDiv = ref(null) // 声明一个空引用变量 return { myDiv } }, mounted() { console.log(this.$el) // 组件的根元素 } } </script></code>
3. querySelector
querySelector
method on the element bound using the Vue instance. <code class="vue"><template> <div></div> </template> <script> import { ref } from 'vue' export default { setup() { // 绑定一个空引用变量 const myDiv = ref(null) return { myDiv } }, mounted() { this.myDiv.value = this.$el.querySelector('div') } } </script></code>
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!