1、watch
第一种写法:
name : function(newVal, oldVal){
console.log('es5写法')
}
第二种写法:
name(newVal, oldVal){
console.log('es6写法')
}
第三种写法:
'name'(newVal, oldVal){
console.log('监听的属性可以写成字符串')
}
第四种写法:
'obj.name'(newVal, oldVal){
console.log('监听对象的某个属性')
}
第五种写法:
obj : {
handler(){
console.log('监听obj对象的变化')
},
deep: true // 是否开始深度监听
}
2、computed
{{total}}
total( ){
return this.info.price * this.info.count
}
{{total(num)}}
total( ){
return function( i ){
return this.price * i
}
}
num : {
get( ){
return this.num
},
set(val){
this.num = val
}
}
computed与方法的区别:
computed有缓存,当多次使用同一个计算属性时,只会执行一次函数,其它的会从缓存中取
方法没有缓存,使用几次就执行几次
computed与watch的区别
computed中不能进行异步操作,watch可以
computed中只要依赖的data中数据发生变化就会执行,是多对1或1对1
watch是监听的属性发生变化,才会执行对应的函数,是1对多或1对1
3、set、delete
{{obj.sex}}
{{obj.age}}
data( ){
return {
obj: {
name: 'age',
age: 18
}
}
}
this.obj.sex = "man" // 不会触发视图更新
delete this.obj.age // 不会触发视图更新
this.$set(this.obj, 'sex', 'man') // 会触发视图更新
this.$delete(this.obj, 'age') // 会触发视图更新
4、filter
文本格式化,可以用在表达式和v-bind中
{{3.1415926 | num}}
num(data){
return data.toFixed(2)
}
{{3.1415926 | num(2)}}
num(data, n){
return data.toFixed(n)
}
全局过滤器
filter.js文件
export function fn1(data){
return data + 1;
}
export function fn2(data){
return data + 2;
}
main.js文件
import * as filters from './filters/filter'
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])
})