我正在学习Vue并在计算属性中使用箭头功能时遇到问题。
我的原始代码工作正常(请参见下面的代码段)。
new Vue({
el: '#app',
data: {
turnRed: false,
turnGreen: false,
turnBlue: false
},
computed:{
switchRed: function () {
return {red: this.turnRed}
},
switchGreen: function () {
return {green: this.turnGreen}
},
switchBlue: function () {
return {blue: this.turnBlue}
}
}
});
.demo{
width: 100px;
height: 100px;
background-color: gray;
display: inline-block;
margin: 10px;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
.blue{
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.js"></script>
<div id="app">
<div class="demo" @click="turnRed = !turnRed" :class="switchRed"></div>
<div class="demo" @click="turnGreen = !turnGreen" :class="switchGreen"></div>
<div class="demo" @click="turnBlue = !turnBlue" :class="switchBlue"></div>
</div>
但是,更改计算属性中的方法后,颜色不会更改(尽管turnRed值仍成功在true和false之间切换)。
这是我的代码:
computed:{
switchRed: () => {
return {red: this.turnRed}
},
switchGreen: () => {
return {green: this.turnGreen}
},
switchBlue: () => {
return {blue: this.turnBlue}
}
}
我使用错误的语法吗?
箭头函数丢失了Vue组件上下文。为了您的功能
methods
,computed
,watch
等,使用对象的功能: