一、watch监听
监控vue实例的变化,监听单个属性,必须在data里面声明,监控变量/对象。
基本数据类型简单监视,复杂数据类型(对象、数组)深度监视。
<input type="text" v-model="msg">
<h1>{{msg}}</h1>
<button @click='stus[0].name="jack"'>改变</button>
data(){
return{
msg:'',
stus:[{name:una}]
}
},
watch:{
//基本数据类型简单监视
msg:function(newV,oldV){
console.log(newV,oldV)
},
//复杂数据类型(对象、数组)深度监视
stus:{
deep:true,//深度监视
handler:function(newV,oldV){//执行函数
console.log(newV[0].name)
}
}
二、computed计算
监控自己定义的变量,该变量不在data里面声明,直接在computed里面定义,然后就可在页面上进行双向数据绑定。监听多个属性,有缓存
.active{
background-color:#66FFFF;
}
<audio :src='getSongSrc' autoplay controls></audio>
<ul>
<li v-for='(item,index) in musicData' :key='index' :class='{active:currentIndex==index}' @click='handlerClivk(index)'>
<h2>{{item.id}}--歌名:{{item.name}}</h2>
<p>{{item.author}}</p>
</li>
</ul>
1、getter
data(){
return{
musicData' :[
{id:1,name:'消愁',author:'毛不易',songSrc:'./static/消愁.mp3'},
{id:2,name:'李白,author:'李荣浩',songSrc:'./static/李白.mp3'},
],
currentIndex:0
}
},
compured:{
//默认只有getter
getSongSrc:function(){
return this.musicData [this.currentIndex].songSrc;//切换歌曲
}
},
methods:{
handlerClick(index){
this.currentIndex=index;
}
}
2、setter
compured:{
//默认只有getter
getSongSrc(){
set(newV){
console.log(newV) //索引
this.currentIndex=newV //改变当前歌曲索引
}
get(){
return this.musicData [this.currentIndex].songSrc;//切换歌曲
}
}
},
methods:{
handlerClick(index){
this.getSongSrc=index;//设置值,调用set方法
}
}
3、带参数的计算
<view class="promotion" v-if="isPromotion(item.products.promotion_list)">
<view class="promotion-item" v-for="(v, k) in item.products.promotion_list" :key="k" :class="v.type !== 2 ? 'bg-gray' : ''">
{{v.name}}
</view>
</view>
computed: {
isPromotion(){
return function(data){
let arr = Object.keys(data);
if(arr.length == 0){
return false
}else{
return true
}
}
}
}