computed 实时监听
默认getter
<!--
* @Author: your name
* @Date: 2020-04-01 17:20:57
* @LastEditTime: 2020-04-01 19:38:33
* @LastEditors: Please set LastEditors
* @Description: 计算属性
* @FilePath: \x\12.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
</style>
</head>
<body>
<div id="app">
<!-- <audio autoplay controls> -->
<p>{{getName}}</p>
<ul>
<li v-for="(item, index) in musicData" @click='clickHandler(index)'>
<h2>{{item.id}} {{item.name}}</h2>
</li>
</ul>
<!-- </audio> -->
</div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
var musicData = [
{id: 1, name: 'yu', author: 'x'},
{id: 2, name: 'xx', author: 'y'}
]
new Vue({
el: "#app",
data() {
return {
musicData: musicData,
currentIndex: 0
}
},
// 实时监听
computed: {
// 计算属性默认只有getter
getName: function() {
return this.musicData[this.currentIndex].name;
}
},
methods: {
clickHandler(index) {
this.currentIndex = index;
}
},
})
</script>
</body>
</html>
setter + getter
<!--
* @Author: your name
* @Date: 2020-04-01 17:20:57
* @LastEditTime: 2020-04-01 19:49:25
* @LastEditors: Please set LastEditors
* @Description: 计算属性
* @FilePath: \x\12.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
ul li.active {
background-color: #77FF77;
}
</style>
</head>
<body>
<div id="app">
<!-- <audio autoplay controls> -->
<p>{{getName}}</p>
<ul>
<li v-for="(item, index) in musicData" @click='clickHandler(index)' :class="{active:currentIndex==index}">
<h2>{{item.id}} {{item.name}}</h2>
</li>
</ul>
<!-- </audio> -->
</div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
var musicData = [{
id: 1,
name: 'yu',
author: 'x'
},
{
id: 2,
name: 'xx',
author: 'y'
}
]
new Vue({
el: "#app",
data() {
return {
musicData: musicData,
currentIndex: 0
}
},
// 实时监听
computed: {
// 计算属性默认只有getter
// getName: function() {
// return this.musicData[this.currentIndex].name;
// }
// setter
getName: {
set: function (newV) {
console.log(newV)
this.currentIndex = newV;
},
get: function () {
return this.musicData[this.currentIndex].name;
}
}
},
methods: {
clickHandler(index) {
// this.currentIndex = index;
console.log(this.getName) // 点语法,get
this.getName = index //点语法,set
}
},
})
</script>
</body>
</html>