hook用法
源码涉及hook的较多,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function callHook (vm, hook) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget();
var handlers = vm.$options[hook];
var info = hook + " hook";
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
invokeWithErrorHandling(handlers[i], vm, null, vm, info);
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
popTarget();
}

监听组件的生命周期

Before

1
2
3
4
5
6
// child.vue
privte mounted() {
this.$emit('parentClick')
}
// parent.vue
<Child @mounted='parentClick'>

After

1
2
3
4
5
6
//child.vue
子组件不需要任何处理
//parent.vue
<Child @hook:mounted='parentClick'>
or
<Child @hook:created='parentClick'>

事件侦听器

问: 页面中定义一个定时器,在哪个阶段清除
答: 在beforeDestory中销毁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Before
mounted() {
this.timer = setInterval(() => {
console.log(1)
}, 3000)
},
beforeDestory() {
clearInterval(this.timer)
}
After
mounted() {
const timer = setInterval(() => {
console.log(1)
}, 3000)
this.$once('hook:beforeDestory', () => {
clearInterval(timer)
})
}

事件销毁

通过$mounted绑定的第三方实例组件销毁

1
2
3
4
5
6
7
8
9
mounted() {
var picker = new Picker({
field: this.$refs.input,
format: 'YYYY-MM-DD'
})
this.$once('hook: beforeDestory', () => {
picker.destory()
})
}