Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js computed property for v-bind:class

I understand how to use v-bind:class if I have a computed function returning true or false.

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.

Currently the value of the button is sync'd to a Vue data property.

<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.

computed: {

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

Thanks in advance

like image 567
Matthew Avatar asked May 20 '16 10:05

Matthew


1 Answers

use methods instead:

export default = {
  methods: {

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

and HTML:

<label v-bind:class="myBtnClass('button1')">
....
<label v-bind:class="myBtnClass('button2')">
like image 58
Linus Borg Avatar answered Oct 18 '22 09:10

Linus Borg