在下面的代码中,我希望所有3个按钮都更新Vue数据对象中的关联属性,但只有最后一个更新。可以使用前两个按钮的方式更新数据吗?
new Vue({
el: "#app",
data: {
counter: 0,
anothercounter: 5
},
methods: {
addone: function(c) {
c = c + 1;
},
addonetocounter: function() {
this.counter = this.counter + 1;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<p>
counter is {{ counter }} : <button @click="addone(counter)">+1</button>
</p>
<p>
anothercounter is {{ anothercounter }} : <button @click="addone(anothercounter)">+1</button>
</p>
<p>
counter is {{ counter }} : <button @click="addonetocounter">+1</button>
</p>
</div>
答案 0 :(得分:3)
您可以使用计算出的属性名称。 Documentation
new Vue({
el: "#app",
data: {
counter: 0,
anothercounter: 5
},
methods: {
addone: function(c) {
this[c] = this[c] + 1;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<p>
counter is {{ counter }} : <button @click="addone('counter')">+1</button>
</p>
<p>
anothercounter is {{ anothercounter }} : <button @click="addone('anothercounter')">+1</button>
</p>
</div>