1、如何监听生命周期函数
Vue项目中,我们通常这样去使用如beforeDestroy之类的生命周期函数:
export default {
data(){
return{
timer:null
}
},
mounted() {
//创建定时器
this.timer = setInterval(()=>{
//...
})
},
updated() {
//...
},
beforeDestroy() {
// 销毁定时器
clearInterval(this.timer);
this.timer=null;
},
methods: {
//...
}
}
缺点:但是,如果创建与销毁定时器之间隔得太远,我们可能会忘记销毁定时器。
(1)内部监听生命周期函数
Vue组件中,$on,$once都可以去监听所有的生命周期钩子函数。
export default {
data(){
return{
timer:null
}
},
mounted() {
let $this=this;
//创建定时器
$this.timer = setInterval(()=>{
//...
})
//监听生命周期函数---beforeDestory
$this.$once('hook:beforeDestory',()=>{ //只触发一次,在第一次触发之后移除监听器
clearInterval($this.timer);
$this.timer = null;
})
}
}
(2)外部监听生命周期函数
如何监听子组件的生命周期钩子?
<template>
<!--组件的所有生命周期钩子都可以通过@hook:钩子函数名 来监听触发-->
<Header @hook:updated="_handleUpdated" />
</template>
<script>
import Header from '../components/Header'
export default {
components: {
Header
},
methods: {
_handleUpdated() {
console.log('Header组件的updated钩子函数被触发');
}
}
}
</script>
2、Vue.observable手写状态管理
首先定义store
import Vue from 'vue'
// 通过Vue.observable创建一个可响应的对象
export const store = Vue.observable({
userInfo: {}
})
// 定义 mutations, 修改属性
export const mutations = {
setUserInfo(userInfo) {
store.userInfo = userInfo
}
}
在组建中使用
<template>
<div>
{{ userInfo.name }}
</div>
</template>
<script>
import { store, mutations } from '../store'
export default {
computed: {
userInfo() {
return store.userInfo
}
},
created() {
mutations.setUserInfo({
name: 'LiHua'
})
}
}
</script>
3、watch知多少
(1)基础用法
watch: {
searchValue(newValue, oldValue) {
if (newValue !== oldValue) {
this._loadData()
}
}
},
methods: {
_loadData() {
// 重新加载数据,此处需要通过函数防抖
}
}
(2)立即触发
页面初始化时,watch不会被触发,我们可能会直接在挂载前后进行初始调用,但是只需配置立即执行属性就可以得到相同效果。
watch: {
searchValue: {
// 通过handler来监听属性变化, 初次调用 newValue为""空字符串, oldValue为 undefined
handler(newValue, oldValue) {
if (newValue !== oldValue) {
this._loadData()
}
},
// 配置立即执行属性
immediate: true
}
}
(3)深度监听
在填写表单数据时,通常需要通过用户是否已填写来改变提交按钮的状态,此时我们只需配置深度监听属性,就会监听表单数据对象里面每一个值的变化。
watch: {
formData: {
// 需要注意,因为对象引用的原因, newValue和oldValue的值一直相等
handler(newValue, oldValue) {
// 在改变提交按钮状态
},
deep: true
}
}
(4)watch 注销
页面切换时,我们应该注销掉原来页面的watch,不然可能导致内置溢出。
const unWatch = this.$watch('formData', () => {
console.log('数据发生了变化')
},
{
deep: true
}
)
unWatch();//手动调用unWatch进行注销
采用此方法,可实现随时监听,随时取消。