<-Home
Vue 实战技巧
选项合并策略,自定义生命周期钩子函数
Vue.config.optionMergeStrategies
添加生命周期钩子函数
const optionMergeStrategies = Vue.config.optionMergeStrategies
// 定义了两个生命周期函数 pageVisible, pageHidden
// 为什么要赋值为 optionMergeStrategies.created呢
// 这个相当于指定 pageVisible, pageHidden 的合并策略与 created的相同(其他生命周期函数都一样)
optionMergeStrategies.pageVisible = optionMergeStrategies.beforeCreate
optionMergeStrategies.pageHidden = optionMergeStrategies.created
执行生命周期
const notifyVisibilityChange = (lifeCycleName, vm) => {
// 生命周期函数会存在$options中,通过$options[lifeCycleName]获取生命周期
const lifeCycles = vm.$options[lifeCycleName]
// 因为使用了created的合并策略,所以是一个数组
if (lifeCycles && lifeCycles.length) {
// 遍历 lifeCycleName对应的生命周期函数列表,依次执行
lifeCycles.forEach(lifecycle => {
lifecycle.call(vm)
})
}
// 遍历所有的子组件,然后依次递归执行
if (vm.$children && vm.$children.length) {
vm.$children.forEach(child => {
notifyVisibilityChange(lifeCycleName, child)
})
}
}
hookEvent ,监听组件生命周期
内部生命周期的监听:通过this.$on(‘hook:hookName’)对生命周期进行监听
export default {
mounted() {
this.chart = echarts.init(this.$el)
// 请求数据,赋值数据 等等一系列操作...
// 监听窗口发生变化,resize组件
window.addEventListener('resize', this.$_handleResizeChart)
// 通过hook监听组件销毁钩子函数,并取消监听事件
this.$once('hook:beforeDestroy', () => {
window.removeEventListener('resize', this.$_handleResizeChart)
})
},
updated() {},
created() {},
methods: {
$_handleResizeChart() {
// this.chart.resize()
}
}
}
外部生命周期监听
<template>
<!--通过@hook:updated监听组件的updated生命钩子函数-->
<!--组件的所有生命周期钩子都可以通过@hook:钩子函数名 来监听触发-->
<custom-select @hook:updated="$_handleSelectUpdated" />
</template>
<script>
import CustomSelect from '../components/custom-select'
export default {
components: {
CustomSelect
},
methods: {
$_handleSelectUpdated() {
console.log('custom-select组件的updated钩子函数被触发')
}
}
}
</script>