不使用计算属性
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>
- Document
- </title>
- </head>
- <body>
- <div id="music">
- <audio muted :src="currentSrc" autoplay="autoplay" controls="controls"
- @ended="nextSongs">
- </audio>
- <ul>
- <li v-for="(item, index) in musicArr" @click="clickHandler(item)">
- <h4>
- 歌名: {{item.name}}
- </h4>
- <p>
- 作者:{{item.author}}
- </p>
- <hr>
- </li>
- </ul>
- </div>
- <script src="./js/vue.js">
- </script>
- <script>
- var songs = [{
- id: 1,
- src: "./audios/1.mp3",
- name: "Bend Your Mind",
- author: "Elysian Fields"
- },
- {
- id: 2,
- src: "./audios/2.mp3",
- name: "Talk Baby Talk",
- author: "Emma Louise"
- },
- {
- id: 3,
- src: "./audios/3.mp3",
- name: "1965",
- author: "Zella Day"
- },
- {
- id: 4,
- src: "./audios/4.mp3",
- name: "岁月神偷",
- author: "金玟岐"
- }]
- var mu = new vue({
- el: "#music",
- data: {
- musicArr: songs,
- currentSrc: "./audios/1.mp3",
- currentIndex: 0,
- },
- methods: {
- clickHandler(item) {
- this.currentSrc = item.src;
- },
- nextSongs() {
- this.currentIndex += 1;
- this.currentSrc = this.musicArr[this.currentIndex].src;
- console.log(this.currentSrc)
- }
- },
- computed: {},
- })
- </script>
- </body>
- </HTML>
使用计算属性
- <!DOCTYPE HTML>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>
- Document
- </title>
- </head>
- <body>
- <div id="music">
- <audio :src="getSrc" autoplay="" controls="" @ended="nextSongs">
- </audio>
- <ul>
- <li v-for="(item, index) in musicArr" @click="clickHandler(index)">
- <h4>
- 歌名: {{item.name}}
- </h4>
- <p>
- 作者:{{item.author}}
- </p>
- <hr>
- </li>
- </ul>
- <button @click="addOne">
- 添加
- </button>
- </div>
- <script src="./js/vue.js">
- </script>
- <script>
- var songs = [{
- id: 1,
- src: "./audios/1.mp3",
- name: "Bend Your Mind",
- author: "Elysian Fields"
- },
- {
- id: 2,
- src: "./audios/2.mp3",
- name: "Talk Baby Talk",
- author: "Emma Louise"
- },
- {
- id: 3,
- src: "./audios/3.mp3",
- name: "1965",
- author: "Zella Day"
- },
- {
- id: 4,
- src: "./audios/4.mp3",
- name: "岁月神偷",
- author: "金玟岐"
- }]
- var mu = new Vue({
- el: "#music",
- data: {
- musicArr: songs,
- currentIndex: 0,
- },
- methods: {
- clickHandler(index) {
- this.currentIndex = index;
- },
- nextSongs() {
- this.currentIndex++;
- },
- addOne() {
- this.musicArr.push({
- id: 5,
- src: "./audios/4.mp3",
- name: "岁 1 月神偷",
- author: "金玟岐"
- })
- },
- },
- computed: {
- getSrc: {
- set: function(newValue) {},
- get: function() {
- return this.musicArr[this.currentIndex].src;
- }
- },
- }
- })
- </script>
- </body>
- </HTML>
计算 data 的属性
来源: http://www.bubuko.com/infodetail-3190202.html