属性计算之setter


categories:

  • vue基础
    tags:
  • setter

属性计算之setter

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>监听属性</title>
    <style>
        body{
            margin: 20px 0 ;
            padding: 20px 0 ;
        }
        ul{
            list-style: none;
        }
        li{
            margin: 15px 0px;
            padding: 10px 15px;
            border: 1px solid #954;
            border-radius: 3px;
        }
        .active{
            background: #6ff;

        }
    </style>
</head>
<body>
<div id="app">
    <audio :src="getCurrentSongsrc" autoplay controls></audio>
    <ul>
        <li v-for="(item,index) in musicData" @click="clickHandler(index)" :class="{active: index == currentIndex }">
            <h2>{{item.id}} - - 歌名:{{item.name}}</h2>
            <p>歌手:{{item.author}}</p>
        </li>

    </ul>
</div>
<script src="./vue.js"></script>
<script>
    var musicData = [
        {id:1,name:'1于荣光-少林英雄',author:'1于荣光',songSrc:'./static/1于荣光-少林英雄.mp3'},
        {id:2,name:'2于荣光-少林英雄',author:'2于荣光',songSrc:'./static/2于荣光-少林英雄.mp3'},
        {id:3,name:'3于荣光-少林英雄',author:'3于荣光',songSrc:'./static/3于荣光-少林英雄.mp3'},
        {id:4,name:'4于荣光-少林英雄',author:'4于荣光',songSrc:'./static/4于荣光-少林英雄.mp3'},
    ];
    new Vue({
        el:'#app',
        data(){
            return {
                musicData:musicData,
                currentIndex:0
            };
        },
        // 实时监控页面数据改变
        computed: {
            // 计算属性默认只有getter
            // getCurrentMusicData:function (){
            //     console.log(this.musicData[this.currentIndex].songSrc);
            //     return this.musicData[this.currentIndex].songSrc;
            // }
            getCurrentSongsrc:{
                set:function (newV) {
                        console.log(newV);
                        this.currentIndex = newV;
                },
                get:function () {
                        // console.log(this.musicData[this.currentIndex].songSrc);
                        return this.musicData[this.currentIndex].songSrc;
                }
            }
        },

        methods:{
            //监控点击事件,修改当前索引
            clickHandler(index){
                // 直接修改数据
                // this.currentIndex = index;
                // this.musicData[0].songSrc = this.musicData[val].songSrc
                this.getCurrentSongsrc = index

            }
        }
    })
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/anyux/p/12203021.html