Mounting hook 允许我们在组件渲染前后访问组件。当然他们不会再服务端渲染被调用。如果您需要在初始化时为组件提取一些数据。 为此而使用created (or created + activated for keep-alive components),特别是如果在服务器端呈现期间需要该数据。
beforeMount
beforeMount钩子在初始渲染发生之前和模板或渲染函数被编译之后运行。
beforeMount() {
console.log(`this.$el doesn't exist yet, but it will soon!`);
console.log(`this.$el is ${this.$el}`);
}
mounted
使用 mounted 钩子,你将拥有访问组件模板能力。mounted 钩子是经常使用的生命周期钩子。我使用最多的方式是在 created 里获取组件需要的数据或者在 mounted 中修改 DOM。
<template>
<p>I'm text inside the component.</p></template><script>export default { mounted() { console.log(this.$el.textContent) // I'm text inside the component.
}}</script>
<script>import MyCreepyAnalyticsService from './somewhere-bad'export default {
destroyed() {
console.log(this) // There's practically nothing here!
MyCreepyAnalyticsService.informService('Component destroyed. All assets move in on target on my mark.')
}}</script>
其他钩子(activated and deactivated)
还有另外两个挂钩,activated and deactivated。 这些是用于保持活动的组件,这个主题不在本文的范围之内。 只要它们允许您检测何时打开或关闭包含在<keep-alive> </ keep-alive>标签中的组件。 您可以使用它们来获取组件的数据或处理状态更改,相当于 created 和 beforeDestroy,而无需执行完整的组件重建。