学习优先度:★★★★★

难易度:★★★★☆

Vue.js 中的挂载生命周期钩子会在实例挂载到 DOM 后调用,从而允许您与渲染的元素进行交互。

下面的示例展示了如何使用挂载钩子:

【代码示例】

new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
},
template: '<div>{{ message }}</div>',
mounted() {
// This function is called after the instance is mounted to the DOM
console.log('Component is mounted.');
console.log('DOM element:', this.$el.textContent);
// Modifying the DOM
this.$el.style.color = 'blue';
}
});

【执行结果】

Console output:
Component is mounted.
DOM element: Hello, Vue!
The text "Hello, Vue!" will be displayed in blue on the page.

挂载钩子在组件渲染完成、插入 DOM 并对用户可见后调用。此时,您可以完全访问组件的 DOM 元素,并安全地执行与 DOM 相关的操作。

这个钩子非常适合需要完全呈现 DOM 的任务,例如

初始化第三方基于 DOM 的库

访问或修改子组件

在 DOM 元素上设置事件监听器

执行 DOM 测量

调用依赖于 DOM 元素的 API

需要注意的是,挂载并不能保证所有子组件也已挂载。如果需要等待整个视图渲染完成,可以在挂载钩子内使用 Vue.nextTick()。

【补充】

在 Vue 3 中,挂载钩子是组件 API 的一部分,可与 onMounted 函数一起使用。这样可以更好地组织大型组件中与生命周期相关的代码。此外,如果您在 Vue 中使用单文件组件(SFC),您可以使用 语法,该语法会将顶层代码隐式地绑定到挂载钩子,从而进一步简化组件逻辑。