一、vue的監聽
1.監聽的例子
如:
html:<input type="number" v-model="a" />
js:
watch: {
//監聽完整寫法
// a: {
// handler: function(){
// console.log('a變化了2');
// }
// }
//a屬性如果發生了變化,a配置函數就會執行
//簡寫
a: function (newVal, oldVal) {
console.log('a變化了1');
console.log(newVal, oldVal);
}
}
2.vue寫一個定時器
methods: {
A: function () {
setInterval(() => {
this.obj.today = new Date;
}, 1000)
}
},
mounted: function () {
this.A();
}
3.vm實例的監聽
//vm實例的方法,對vm的屬性即相關的函數執行監聽
// 參數1:監聽的值
// 參數2:回調
vm.$watch(function(){
//this指向實例對象
var count = this.a + this.b;
return '';
}, function(newVal, oldval){
console.log("變化了");
console.log(newVal, oldval);
}, {
deep: true
});
二、實例的生命周期
methods: {
testAction(){
console.log('testAction調用');
},
modifyAction(){
console.log('修改');
this.message = 'hello world';
//屬性發生變化,監聽dom更新完成的事件
// 屬性修改后,不要任何代碼,執行監聽
this.$nextTick(()=>{
console.log('nextTick執行');
});
console.log(this.message);
console.log(this.$refs.info1.innerText);
//更新輪播,滾動
},
updateAction(){
this.$forceUpdate();
}
},
//實例創建前,什么也做不了
beforeCreate(){
console.log('beforeCreate執行了');
// console.log(this.message);
// this.testAction();
},
created(){
console.log('created執行了');
// this.obj.name = '123456';
},
beforeMount(){
console.log('beforeMount執行了');
// console.log(document.querySelector('.info1').innerText);
// console.log(this.$refs);
// console.log(this.$refs.info1);
// console.log(this.$refs.info2);
},
mounted(){
console.log('mounted執行了');
console.log(document.querySelector('.info1').innerText);
console.log(this.$refs);
},
// 更新前,dom更新前
beforeUpdate(){
console.log('beforeUpdate執行了');
console.log(this.message);
},
//更新完成,dom更新后
updated() {
console.log('updated執行了');
console.log(this.message);
//更新輪播,滾動的事件
},
beforeDestroy(){
console.log('beforeDestroy執行了');
},
destroyed(){
console.log('destroyed執行了');
}
});
/*
創建:
1.new Vue();
2.讀取生命周期函數
3.beforeCreate()
4.加載data,computed,watch,methods....添加屬性的數據觀測
5.created()
掛載:
6.判斷是否有$sel/等待$mount()調用
7.beforeMount()
8.渲染dom結構
9.mounted()
//在mounted之后操作dom結構,但是不用使用document訪問dom。
// 操作dom的方式使用ref給dom賦值,通過$refs訪問
更新:更新的鈎子函數中不要修改屬性。
10.屬性發生了變化
11.beforeUpdate() dom更新前
12.重新渲染dom,dom進行更新
13.updated() dom更新完畢
//如果數據變化,要操作更新后的dom結構,使用$nextTick()
// 銷毀:
14:beforeDestroy()
15.移除事件監聽,綁定
16.destroyed()
$refs:獲得vm實例作用下的dom
$nextTick()數據發生變化后,監聽dom更新完畢的事件
$forceUpdate()強制更新dom