Frank Provost Frank Provost - 1 month ago 26
Javascript Question

Vue.js add property to bound object

I have an list like this one

<div class="list-group entity-list">

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


The list is displayed as expected. The Bound entity is added as an prop to an outer compontent like this.

<my-compontent :entityname="customers" :master="{{json_encode($customers->toArray())}}" inline-template>


As you can see it should be a list of customers. To indicate if a customer is selected i want to set an "selected" attribute on click. However it does not seem to work if the default bound object does not have a select property.

methods: {
itemselect: function(item) {
this.master.data.forEach(function(el) {
el.selected = false;
});

item.selected = true;
}
}


The shown method does not seem to work / trigger a change

Answer

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/

Comments