vue 里面进行dom操作
在 Vue 中进行 DOM 操作有以下几种方式:
- 直接在模板中使用指令或者表达式进行 DOM 操作,例如:
<template>
<div>
<p v-if="show">显示的内容</p>
<button @click="toggleShow">切换显示状态</button>
</div>
</template>
<script>
export default {
data() {
return {
show: true
}
},
methods: {
toggleShow() {
this.show = !this.show
}
}
}
</script>
- 使用 Vue 提供的 $refs 属性获取 DOM 元素,然后进行操作,例如:
<template>
<div>
<input type="text" ref="input">
<button @click="focusInput">聚焦输入框</button>
</div>
</template>
<script>
export default {
methods: {
focusInput() {
this.$refs.input.focus()
}
}
}
</script>
- 使用第三方插件或者库来进行 DOM 操作,例如 jQuery 等。
需要注意的是,Vue 推荐使用数据驱动视图的思想来进行开发,尽量避免直接操作 DOM,以避免出现一些不可预料的问题。
原文地址: https://www.cveoy.top/t/topic/7kn 著作权归作者所有。请勿转载和采集!