如何用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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM