vue基础(三):监听、计算

一、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
					}
				}
			}
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值