如何在Vue.js类绑定上检查当前元素的属性?

时间:2017-06-02 10:11:41

标签: javascript vue.js

我是Vue.js的总菜鸟,我正在尝试构建某种漂亮的自定义选项选择器。

我的数据绑定工作正常,但我无法弄清楚类绑定如何用于检查每个节点的值。

HTML:

<div id="pretty_options">
  <ul class="pretty-options" data-field="field_id">
    <li class="option" v-on:click="select" v-bind:class="{ selected : isSelected }" data-value="1">One</li>
    <li class="option" v-on:click="select" v-bind:class="{ selected : isSelected }" data-value="2">Two</li>
    <li class="option" v-on:click="select" v-bind:class="{ selected : isSelected }" data-value="3">Three</li>
    <li class="option" v-on:click="select" v-bind:class="{ selected : isSelected }" data-value="4">Four</li>
    <li class="option" v-on:click="select" v-bind:class="{ selected : isSelected }" data-value="5">Five</li>
  </ul>
  <input type="number" id="field_id" name="field_id" v-model="field_id">
</div>  

JS:

var mcveSample = new Vue({
  el: '#pretty_options',
  data: {
    field_id: 1
  },
  methods: {
    select: function(event) {
      var option = event.currentTarget;
      var value = option.dataset.value;
      this.field_id = value;
    }
  },
  computed: {
    isSelected: function(element) {
      // I'd like to do something like this:
      // return this.field_id == element.dataset.value;
      // But, I can't find how to check each element's value...
    }
  }
});

这是JSFiddle

所以,我的问题是:如何与计算函数上的每个节点的值/属性进行比较?

1 个答案:

答案 0 :(得分:2)

Computed属性返回基于另一个数据属性或计算值的值。在您的情况下,您应该使用一个接受li索引作为参数并返回true / false的方法,或者只检查内联等式。

此外,您可以使用v-for生成列表项:

&#13;
&#13;
var mcveSample = new Vue({
  el: '#pretty_options',
  data: {
    field_id: 0,
    options: ['One', 'Two', 'Three', 'Four', 'Five']
  },
  methods: {
    select: function(index) {
      this.field_id = index;
    }
  }
});
&#13;
.option {
  display: inline-block;
  list-style: none;
  margin: 1em;
  padding: 0.25em 1em;
  background-color: #ccc;
  border-radius: 1em;
  cursor: default;
}
.selected {
  background-color: red;
}
&#13;
<script src="https://unpkg.com/vue"></script>
    
<div id="pretty_options">
    <ul class="pretty-options" data-field="field_id">
      <li class="option" 
        v-for="(option, index) of options" // create li from your array
        v-on:click="select(index)" 
        v-bind:class="{ selected : index == field_id }" // check inline for example
        v-bind:data-value="index">{{ option }}</li>
    </ul>
    <input type="number" id="field_id" name="field_id" v-model="field_id">
</div>
&#13;
&#13;
&#13;

如果你更喜欢method和/或你需要更复杂的逻辑,你可以这样做:

v-bind:class="{ selected : isSelected(index) }"

并定义此方法:

methods: {
  isSelected: function(index) {
    return index == this.field_id
  },
//...other methods
}

或者最好使用返回函数的计算属性

computed:{
  isSelected: function() {
    return function(index){
       return index == this.field_id;
    }
  },
  //...other computed propertues
}

Documentation

  

计算属性根据其依赖性进行缓存