【问题标题】:Vue.js computed property for v-bind:classv-bind:class 的 Vue.js 计算属性
【发布时间】:2016-09-17 13:20:15
【问题描述】:

如果我有一个返回 true 或 false 的计算函数,我了解如何使用 v-bind:class。

我想知道是否可以使用与被单击按钮的 ID 和该按钮的值相匹配的计算属性。 因此,单击按钮 1 我可以获得该按钮的值并检查它是否与绑定到输入的数据模型的值匹配。

当前按钮的值已同步到 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

这一点只适用于一个按钮,显然我不想重复这段代码x次。

computed: {

myBtnClass: function () {
            var result = [];
            if (this.valueOfBtn) == document.getElementById('button1').value.valueOf()))
            {
                result.push('primary');
            }
            return result;

提前致谢

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    改用methods

    export default = {
      methods: {
    
        myBtnClass: function(name) {
          var result = [];
          if (this.valueOfBtn) === name) {
            result.push('primary');
          }
          return result;
        },
      // ...
      }
    }
    

    和 HTML:

    <label v-bind:class="myBtnClass('button1')">
    ....
    <label v-bind:class="myBtnClass('button2')">
    

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 2017-11-01
      • 2021-03-05
      • 2020-11-04
      • 2017-08-26
      • 1970-01-01
      • 2019-08-08
      • 2017-10-06
      • 2017-10-07
      相关资源
      最近更新 更多