[Vuejs]-Vue.js add property to bound object

1👍

If you want to modify data passed in by a prop then you need to copy it, vue will throw out a warning if you try to directly modify a prop. I would probably handle this by doing something like:

new Vue({
  el: '#app',
  created() {
    // Assume this is passed in by a prop
      var myData = {master: {
        data: [{
          name: 'foo'
        }, {
          name: 'bar'
        }, {
          name: 'baz'
        }]
      }};

    // Copy data from prop
    myData.master.data.forEach(el => {
      var obj = {
        name: el.name,
        selected: false
      };

      this.master.data.push(obj);
    });
  },
  methods: {
    itemselect(item) {
      this.master.data.forEach(el => {
        // if this element is selected set to true      
        el['selected'] = (el.name == item.name);
      });
    }
  },
  data() {
    return {
      master: {
        data: []
      }
    }
  }
});

I just mocked the actual data coming in, but obviously this would add this to a prop and pass it to your component as usual. Here’s the jsFiddle: https://jsfiddle.net/xswtfkaf/

1👍

Instead of altering your master data, track selection in model, using $index assuming you don’t reorder your master.data

<div class="list-group entity-list">
    <a  v-for="entity in master.data"
        :class="eClass[$index]"
        @click="itemselect($index)"
            >
        @{{entity.name}}
    </a>
</div>

methods: {
    itemselect: function(idx) {
        if ( 0 > this.selected.indexOf(idx) ) {
            this.selected.push(idx)
        }
    }
}
computed : {
    eClass : function () {
        var r=[];
        for (var i= 0;c=this.master.data[i];++i) {
            r[i] = {'selected': -1 < this.selected.indexOf(i),'entity list-group-item':true};
        }
        return r;
    }
}

if entity has am unique id

<div class="list-group entity-list">
    <a  v-for="entity in master.data"
        :class="eClass[entity.id]"
        @click="itemselect(entity.id)"
            >
        @{{entity.name}}
    </a>
</div>

methods: {
    itemselect: function(idx) {
        if ( 0 > this.selected.indexOf(idx) ) {
            this.selected.push(idx)
        }
    }
}
computed : {
    eClass : function () {
        var r={};
        for (var i= 0;c=this.master.data[i];++i) {
            r[c.id] = {'selected': -1 < this.selected.indexOf(c.id),'entity list-group-item':true};
        }
        return r;
    }
}
👤cske

Leave a comment