0

I am building something with VueJS and I have some problem to select an item in a list:

Let's imagine the following VueJS component:

new Vue({
    el: '#app',
  data: {
    list: [
        {
        id: 1,
        title: 'My first Item',
        selected: false
      },
      {
        id: 2,
        title: 'My second Item',
        selected: false
      }
    ]
  }
})

With the selected property, I can apply a class or not to the item:

<div id="app">
  <ul>
    <li @click="item.selected = !item.selected" :class="item.selected ? 'active' : ''" v-for="item in list">{{ item.title }}</li>
  </ul>
</div>

But now, let's imagine that I grab my data from an API, I still want to be able to select the items:

new Vue({
    el: '#app',
  data: {
    list: []
  },
  created: function () {
    // Let's imagine that this is an Ajax Call to a webservice
    this.$set('list', [
      {
        id: 1,
        title: 'My first Item'
      },
      {
        id: 2,
        title: 'My second Item'
      }
    ])
  }
})

Now, my html can't work anymore because the data has not a selected property.

So how could I do such a thing?

Here are two JsFiddle that explain the problem:

Hammerbot
  • 15,696
  • 9
  • 61
  • 103
  • This is very similar to an answer I posted here: http://stackoverflow.com/questions/39778665/vue-js-v-show-in-a-list/39779332#39779332 – Bill Criswell Oct 01 '16 at 15:49

1 Answers1

0

Please read docs on vue lifecycle :

id prefer you set the list to be a computed property that always checks for returned items : ie ,

new Vue({
    el: '#app',
  data: {
    list: []
  },
  computed: {
   list (){
    // Let's imagine that this is an Ajax Call to a webservice
    let returned =  [
      {
        id: 1,
        title: 'My first Item'
      },
      {
        id: 2,
        title: 'My second Item'
      }
    ]
     return returned
   }
  }
})
Jimmy Obonyo Abor
  • 7,335
  • 10
  • 43
  • 71