zoukankan      html  css  js  c++  java
  • 如何学习vue的计算属性computed

    vue的计算属性computed
    任何复杂逻辑,在vue里都应当使用计算属性computed,计算属性是方法而不是属性,我们可以将同一函数定义为一个方法而不是一个计算属性。两种方式的最终结果确实是完全相同的。然而,不同的是计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。下面是一个小demo,有助于大家理解和运用computed属性

    <!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){
    						this.currentIndex=index;
    					}
    				},
    				computed:{
    					getCurrentsong:function(){
    						return this.musicData[this.currentIndex].songSrc
    					}
    				}
    			})
    		</script>
    	</body>
    </html>
    
    
  • 相关阅读:
    git commit --amend
    Interleaving String leetcode
    Longest Common Substring
    Distinct Subsequences Leetcode
    Longest Common Subsequence
    Palindrome Partitioning II Leetcode
    百度面试时遇到这样一个问题:给定数组a[];计算除最后一个元素之外其他元素的和,下面的代码有什么问题吗
    sizeof与strlen
    网络是怎么连接的(2)?
    网络是怎么连接的(1)?
  • 原文地址:https://www.cnblogs.com/lxystar/p/10724277.html
Copyright © 2011-2022 走看看