如何用vue的computed的set和get方法

如何用vue的computed的set和get方法
默认只有getter可以获取值
对计算属性设置值,会调用计算属性的setter方法

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../node_modules/vue/dist/vue.js"></script>
		<style>
			li{list-style: none;}
			.active{background:red;}
		</style>
	</head>
	<body>
		<div id="app">
			<audio :src="getCurrentsong" autoplay="autoplay" controls="controls"></audio>
			<ul>
				<li v-for="(song,index) in musicData" :class="{active:index==currentIndex}"  @click="clickHandler(index)">
					<h2>{{song.id}}--{{song.name}}</h2>
					<h3>{{song.songSrc}}</h3>
				</li>
			</ul>
		</div>
		<script type="text/javascript">
			var musicData = [
			    {
			        id: 1,
			        name: "I believe",
			        songSrc: "../music/I believe.mp3",
			        author: "杨培安"
			    },
			    {
			        id: 2,
			        name: "一百万个可能.mp3",
			        songSrc: "../music/一百万个可能.mp3",
			        author: "Skot Suyama"
			    },
			    {
			        id: 3,
			        name: "I believe",
			        songSrc: "../music/I believe.mp3",
			        author: "杨培安"
			    }
			];
			new Vue({
				el:"#app",
				data(){
					return{
						musicData,
						currentIndex:0
					}
				},
				methods:{
					clickHandler(index){
						//可以获取computed的方法的值
						this.getCurrentsong=index;
					}
				},
				computed:{
					getCurrentsong:{
						get:function(){
							return this.musicData[this.currentIndex].songSrc
						},
						set:function(val){
							this.currentIndex=val;
						}		
					}
				}
			})
		</script>
	</body>
</html>

posted @ 2019-04-17 16:39  lxystar  阅读(5083)  评论(0编辑  收藏  举报