在 vue 中,获取 dom 元素有三种方法:1. 使用 ref 属性为元素指定引用变量,并通过 this.$refs 访问;2. 直接使用组件的根元素 this.$el;3. 使用 queryselector 方法在绑定元素上查询。
在 Vue 中获取 DOM 元素
在 Vue 应用中,可以通过以下方法获取 DOM 元素:
1. ref 属性
- 为组件或元素添加
ref
属性,并指定一个引用变量名。 - 在 Vue 实例中,可以使用
this.$refs
对象访问带有ref
属性的元素。
<code class="<a style='color:#f60; text-decoration:underline;' href=" https: target="_blank">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>
2. $el 属性
-
$el
属性指向当前组件的根元素。
<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>
3. querySelector
- 使用 Vue 实例绑定的元素上调用
querySelector
方法。
<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>