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>
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。