vue实现访问html
Vue 实现访问 HTML 的方法
Vue 提供了多种方式访问和操作 HTML 元素,以下是几种常见的方法:
使用 ref 属性获取 DOM 元素
在 Vue 模板中,可以通过 ref 属性标记元素,然后在 JavaScript 中通过 $refs 访问对应的 DOM 节点。

<template>
<div ref="myElement">这是一个 DOM 元素</div>
</template>
<script>
export default {
mounted() {
console.log(this.$refs.myElement); // 获取 DOM 元素
this.$refs.myElement.style.color = 'red'; // 修改样式
}
}
</script>
使用 v-html 指令渲染 HTML
如果需要动态渲染 HTML 字符串,可以使用 v-html 指令。注意:避免直接渲染用户输入的内容,以防止 XSS 攻击。

<template>
<div v-html="rawHtml"></div>
</template>
<script>
export default {
data() {
return {
rawHtml: '<span style="color: red">红色文本</span>'
}
}
}
</script>
使用 document.querySelector 直接访问
虽然不推荐,但在某些情况下可以直接使用原生 DOM API 访问元素。
<template>
<div id="myElement">直接访问的元素</div>
</template>
<script>
export default {
mounted() {
const element = document.getElementById('myElement');
element.textContent = '内容已修改';
}
}
</script>
使用 Vue 的模板引用
在组合式 API 中,可以使用 ref 和 template ref 结合的方式访问元素。
<template>
<div ref="myDiv">组合式 API 访问</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const myDiv = ref(null);
onMounted(() => {
console.log(myDiv.value); // 访问 DOM 元素
});
</script>
注意事项
- 优先使用 Vue 提供的
ref和$refs机制,而不是直接操作 DOM。 - 使用
v-html时要确保内容安全,避免 XSS 风险。 - 在组件生命周期钩子(如
mounted)中访问 DOM,确保元素已渲染完成。






