Javascript v-bind:class 的 Vue.js 计算属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37343923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue.js computed property for v-bind:class
提问by Matthew
I understand how to use v-bind:class if I have a computed function returning true or false.
如果我有一个返回 true 或 false 的计算函数,我了解如何使用 v-bind:class。
I would like to know if it is possible to use a computed property that matches the ID of the button being clicked and the value of that button. So clicking button 1 I could get the value of of that button and check if it matches the value of data model being bind to the input.
我想知道是否可以使用与被单击按钮的 ID 和该按钮的值相匹配的计算属性。因此,单击按钮 1 我可以获得该按钮的值并检查它是否与绑定到输入的数据模型的值匹配。
Currently the value of the button is sync'd to a Vue data property.
目前,按钮的值已同步到 Vue 数据属性。
<label v-bind:class="myBtnClass">
<input type="radio" name="button1" id="button1" value="1" v-model="valueOfBtn"> One
</label>
<label v-bind:class="myBtnClass">
<input type="radio" name="button2" id="button2" value="2" v-model="valueOfBtn"> Two
</label>
new Vue({
el: '#app',
data: {
'valueOfBtn': 1
This bit would only work for one button and clearly I don't want to repeat this block of code x times.
此位仅适用于一个按钮,显然我不想重复此代码块 x 次。
computed: {
myBtnClass: function () {
var result = [];
if (this.valueOfBtn) == document.getElementById('button1').value.valueOf()))
{
result.push('primary');
}
return result;
Thanks in advance
提前致谢
回答by Linus Borg
use methods
instead:
使用methods
来代替:
export default = {
methods: {
myBtnClass: function(name) {
var result = [];
if (this.valueOfBtn) === name) {
result.push('primary');
}
return result;
},
// ...
}
}
and HTML:
和 HTML:
<label v-bind:class="myBtnClass('button1')">
....
<label v-bind:class="myBtnClass('button2')">