Home > Web Front-end > Vue.js > body text

How to get dom elements in vue

下次还敢
Release: 2024-04-30 04:09:15
Original
563 people have browsed it

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.

How to get dom elements in vue

Get DOM elements in Vue

In Vue applications, you can get DOM elements through the following methods:

1. ref attribute

  • Add the ref attribute to a component or element and specify a reference variable name.
  • In a Vue instance, you can use the 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>
Copy after login

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>
Copy after login

3. querySelector

  • Call the 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>
Copy after login

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!

Related labels:
vue
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!