Vue 3 官方文档(中文版)
返回
0
生命周期和模板引用
目前为止,Vue 为我们处理了所有的 DOM 更新,这要归功于响应性和声明式渲染。然而,有时我们也会不可避免地需要手动操作 DOM。
这时我们需要使用模板引用——也就是指向模板中一个 DOM 元素的 ref。我们需要通过这个特殊的 ref attribute 来实现模板引用:
<p ref="pElementRef">hello</p>
组合式 API
要访问该引用,我们需要声明并暴露一个同名的 ref:
const pElementRef = ref(null)
setup() {
const pElementRef = ref(null)
return {
pElementRef
}
}
注意这个 ref 使用 null 值来初始化。这是因为当 <script setup>``setup() 执行时,DOM 元素还不存在。模板引用 ref 只能在组件挂载后访问。
要在挂载之后执行代码,我们可以使用 onMounted() 函数:
import { onMounted } from 'vue'
onMounted(() => {
// 此时组件已经挂载。
})
import { onMounted } from 'vue'
createApp({
setup() {
onMounted(() => {
// 此时组件已经挂载。
})
}
})
选项式 API
此元素将作为 this.$refs.pElementRef 暴露在 this.$refs 上。然而,你只能在组件挂载之后访问它。
要在挂载之后执行代码,我们可以使用 mounted 选项:
export default {
mounted() {
// 此时组件已经挂载。
}
}
createApp({
mounted() {
// 此时组件已经挂载。
}
})
这被称为生命周期钩子——它允许我们注册一个在组件的特定生命周期调用的回调函数。还有一些其他的钩子如 created 和 updated / onUpdated 和 onUnmounted。更多细节请查阅生命周期图示。
现在,尝试添加一个 mounted / onMounted 钩子,然后通过 this.$refs.pElementRef / pElementRef.value 访问 <p>,并直接对其执行一些 DOM 操作。(例如修改它的 textContent)。
共 124 篇
Vue 3 官方文档(中文版)
/
生命周期和模板引用
0 字
0 行
cosolar
创建
2026-11-08T09:54:58.599508772Z
更新
2026-11-08T09:57:33.577814166Z