生命周期挂钩是了解您正在使用的库如何在幕后工作的窗口。生命周期钩子允许您知道组件何时被创建、添加到 DOM、更新或销毁。
本文将向您介绍 Vue.js 中的创建、安装、更新和销毁钩子。
要完成本教程,您需要:
- 熟悉 Vue.js。阅读如何使用 Vue.js 开发网站系列以了解更多信息。
创作挂钩是在组件中运行的第一个钩子。它们允许您在组件添加到 DOM 之前执行操作。与任何其他挂钩不同,创建挂钩也在服务器端渲染期间运行。
如果您需要在客户端渲染和服务器渲染期间在组件中进行设置,请使用创建挂钩。
您将无权访问 DOM 或目标安装元素(this.$el
) 在创建挂钩内。
The beforeCreate
钩子在组件初始化时运行 -data
尚未做出反应,并且events
尚未设置:
示例组件.vue
<script>
export default {
beforeCreate() {
console.log('At this point, events and lifecycle have been initialized.')
}
}
</script>
在此示例中,当beforeCreate
挂钩运行后,此代码片段将记录消息:
Output
At this point, events and lifecycle have been initialized.
The created
钩子在模板和虚拟 DOM 被安装或渲染之前运行 - 您可以访问响应式data
and events
活跃的:
示例组件.vue
<template>
<div ref="example-element">{{ propertyComputed }}</div>
</template>
<script>
export default {
data() {
return {
property: 'Example property.'
}
},
computed: {
propertyComputed() {
return this.property
}
},
created() {
console.log('At this point, this.property is now reactive and propertyComputed will update.')
this.property = 'Example property updated.'
}
}
</script>
在此示例中,片段将存储property
as Example property
。当。。。的时候created
钩子运行后,它会记录一条消息:
Output
At this point, this.property is now reactive and propertyComputed will update.
进而property
更改为Example property updated
.
在生命周期的后期,{{ propertyComputed }}
将显示为Example property updated
代替Example property
.
在此步骤中,您查看了创建挂钩的一些示例,并准备好进入生命周期的下一部分:安装挂钩。
安装挂钩通常是最常用的钩子。它们允许您在第一次渲染之前和之后立即访问您的组件。但是,它们不会在服务器端渲染期间运行。
如果您需要在初始渲染之前或之后立即访问或修改组件的 DOM,请使用安装挂钩。
如果您需要在初始化时为组件获取一些数据,请不要使用安装挂钩。
Note: Use created
(or created
and activated
for keep-alive
组件)为此。特别是当您在服务器端渲染期间需要该数据时。
The beforeMount
钩子在初始渲染发生之前以及模板或渲染函数编译之后运行:
示例组件.vue
<script>
export default {
beforeMount() {
console.log(`At this point, vm.$el has not been created yet.`)
}
}
</script>
在此示例中,当beforeMount
挂钩运行后,此代码片段将记录消息:
Output
At this point, vm.$el has not been created yet.
In the mounted
钩子后,您将可以完全访问反应式组件、模板和渲染的 DOM(通过this.$el
).
Use mounted
用于修改 DOM,特别是在集成非 Vue 库时:
示例组件.vue
<template>
<div ref="example-element">Example component.</div>
</template>
<script>
export default {
mounted() {
console.log(`At this point, vm.$el has been created and el has been replaced.`);
console.log(this.$el.textContent) // Example component.
}
}
</script>
在此示例中,当mounted
挂钩运行后,此代码片段将记录消息:
Output
At this point, vm.$el has been created and el has been replaced.
另外,还有一条消息Example content.
(this.$el.textContent
)将被记录。
在本节中,您探索了安装挂钩的用例。在下一步中,您将查看一些使用更新挂钩的示例。
更新挂钩每当组件使用的反应性属性发生更改或其他原因导致其重新渲染时,就会调用。它们允许您连接到观察-计算-渲染为您的组件循环。
如果您需要知道组件何时重新渲染(可能是为了调试或分析),请使用更新挂钩。
如果您需要知道组件上的反应性属性何时发生变化,请不要使用更新挂钩。使用计算属性 or watchers为此。
The beforeUpdate
钩子在组件上的数据更改之后运行,更新周期开始,就在 DOM 修补和重新渲染之前。
Use beforeUpdate
如果您需要在渲染之前获取组件上任何反应数据的新状态:
示例组件.vue
<template>
<div ref="example-element">{{counter}}</div>
</template>
<script>
export default {
data() {
return {
counter: 0
}
},
created() {
setInterval(() => {
this.counter++
}, 1000)
},
beforeUpdate() {
console.log(`At this point, Virtual DOM has not re-rendered or patched yet.`)
// Logs the counter value every second, before the DOM updates.
console.log(this.counter)
}
}
</script>
首先,这个片段将存储counter
as 0
。当。。。的时候created
钩子运行后,它会增加counter
every 1000
多发性硬化症。当。。。的时候beforeUpdate
挂钩运行后,此代码片段将记录消息:
Output
At this point, Virtual DOM has not re-rendered or patched yet.
和一个数字counter
也已记录。
The updated
钩子在组件上的数据更改和 DOM 重新渲染后运行。
Use updated
如果您需要在属性更改后访问 DOM:
示例组件.vue
<template>
<div ref="example-element">{{counter}}</div>
</template>
<script>
export default {
data() {
return {
counter: 0
}
},
created() {
setInterval(() => {
this.counter++
}, 1000)
},
updated() {
console.log(`At this point, Virtual DOM has re-rendered and patched.`)
// Fired every second, should always be true
console.log(+this.$refs['example-element'].textContent === this.counter)
}
}
</script>
首先,这个片段将存储counter
as 0
。当。。。的时候created
钩子运行后,它会增加counter
every 1000
多发性硬化症。当。。。的时候updated
挂钩运行后,此代码片段将记录消息:
Output
At this point, Virtual DOM has re-rendered and patched.
和一个布尔值true
被记录是因为渲染值和当前值相等。
现在您已经探索了更新钩子的使用,您准备好了解销毁钩子了。
破坏钩允许您在组件被破坏时执行操作,例如清理或发送分析。当您的组件被拆除并从 DOM 中删除时,它们会触发。
beforeDestroy
在拆卸前被解雇。您的组件仍将完全存在并正常运行。
Use beforeDestroy
如果您需要清理事件或反应式订阅:
示例组件.vue
<script>
export default {
data() {
return {
exampleLeakyProperty: 'This represents a property that will leak memory if not cleaned up.'
}
},
beforeDestroy() {
console.log(`At this point, watchers, child components, and event listeners have not been teared down yet.`)
// Perform the teardown procedure for exampleLeakyProperty.
// (In this case, effectively nothing)
this.exampleLeakyProperty = null
delete this.exampleLeakyProperty
}
}
</script>
该片段将首先存储exampleLeakyProperty
。当。。。的时候beforeDestroy
挂钩运行后,此代码片段将记录消息:
Output
At this point, watchers, child components, and event listeners have not been torn down yet.
进而exampleLeakyProperty
被删除。
当您到达destroyed
钩子,你的组件上几乎没有剩下任何东西了。附着在它上面的一切都被摧毁了。
Use destroyed
如果您需要进行最后一刻的清理或通知远程服务器该组件已被破坏:
示例组件.vue
<script>
import ExampleAnalyticsService from './example-analytics-service'
export default {
destroyed() {
console.log(`At this point, watchers, child components, and event listeners have been torn down.`)
console.log(this)
ExampleAnalyticsService.informService('Component destroyed.')
}
}
</script>
首先,这个片段将导入ExampleAnalyticsService
。当。。。的时候beforeDestroy
挂钩运行后,此代码片段将记录消息:
Output
At this point, watchers, child components, and event listeners have been torn down.
组件的剩余部分将被记录到控制台,并且ExampleAnalyticsService
将传递消息Component destroyed.
.
至此,您已经完成了对 Vue.js 生命周期挂钩的总体回顾。
还有另外两个钩子,activated
and deactivated
。这些是为了keep-alive
组件,这个主题超出了本文的范围。
只要说它们允许您检测包装在<keep-alive></keep-alive>
标签已打开或关闭。您可以使用它们来获取组件的数据或处理状态更改,有效地表现为created
and beforeDestroy
无需进行完整的组件重建。
在本文中,我们向您介绍了 Vue.js 实例生命周期中可用的不同生命周期挂钩。您探索了创建钩子、安装钩子、更新钩子和销毁钩子的不同用例。
如果您想了解有关 Vue.js 的更多信息,请查看我们的 Vue.js 主题页面用于练习和编程项目。