computed计算属性
规则:
1.用已有的属性计算不存在的属性
2.默认调用一次get()
3.简写时注意:
只有值不发生改变
才可以是用简写(函数),值发生改变必须使用对象,才可以配置set()方法
4.底层原理
使用
Object.definproperty(目标对象,键名,{get(){},set(value){}})
computed:{
str(){
return this.bool?"炎热":"凉爽"
}
},
来回切换输入 :炎热/凉爽
watch监听属性___时时监听
规则:
1.监听已存在的属性
2.immediate:true默认调用一次,false不会
3.简写:只有handler方法才可以简写。写法:监听的属性(新值,旧值){}
4.监听对象中的值需要深度监听,deep:true
watch监听属性_computed计算属性 区别:
1.computed能做的watch都可以做,watch可以做的,computed不一定能做
2.使用vm.$watch方法时,需要使用普通函数
3.对于定时器,函数回调,ajax回调,promise回调,建议使用箭头函数
- 代码演示:
// 计算属性
computed:{
},
// 监听属性
watch:{
},
生命周期
1.生命周期函数,钩子函数
2.生命周期函数命名不能修改
3.this指向Vue实例(vm)
生命周期中属性:
beforeCreate | 初始化之前 ,不能获取data中的数据 |
---|---|
created | 初始化之后 ,获取data中的数据 |
beforeCreate() {
console.log(this.userName);
console.log(this.sum());
},
created() {
console.log(this.userName);
console.log(this.sum());
},
beforeMount | 解析前/挂载前 |
---|---|
mounted | 解析后/挂载后 |
beforeMount() {
this.bool = false;
document.getElementsByClassName("box")[0].style.color = "red";
},
mounted() {
this.userName = "王五";
document.getElementsByClassName("box")[0].style.color = "red";
this.timeValue = setInterval(()=>{
this.opacity-=0.01;
if(this.opacity<=0){
this.opacity=1;
}
},10)
},
beforeUpdate | 更新前 |
---|---|
updated | 更新后 |
beforeUpdate() {
setTimeout(()=>{
this.userName = "李四";
},1000)
},
updated() {
this.userName = "王五";
},
beforeDestroy | 销毁前 |
---|---|
destroyed | 销毁后 |
beforeDestroy() {
clearInterval(this.timeValue);
console.log("触发了销毁前");
},
destroyed() {
console.log("触发了销毁后");
},
filters过滤器分两种:
1.局部过滤器
写法:new Vue ( { filters:{名称 ( value ){} }}),
2.全局过滤器
写法:Vue.filter ( "名称 " , function ( value ){})