Vue 'beforeMount' 生命周期钩子
示例
使用 beforeMount 和 mounted 生命周期钩子来演示,在 mounted 钩子之前,组件的 DOM 元素是不可用的。
export default {
data() {
return {
refsObj1: '',
refsObj2: ''
}
},
beforeMount() {
this.refsObj1 = this.$refs; // The $refs object is empty at this point
},
mounted() {
this.refsObj2 = this.$refs;
}
}
运行示例 »
定义和用法
在组件 mounted 之前,也就是在组件添加到 DOM 之前,会执行 beforeMount 生命周期钩子。
因为组件尚未 mounted,所以我们可以访问组件实例内的属性,如 data 或 computed,但无法访问组件的 DOM 元素,因为它们尚未挂载。
相关页面
Vue 教程:Vue 生命周期钩子
Vue 教程:'beforeMount' 钩子
Vue 教程:'mounted' 钩子