onedkr
onedkr

Reputation: 3386

Vue.js Push doesn't update view

I create a array which contains objects describing information of buttons. In my template I have a class active which is represent the active button. By default the first button of the array is active.

template:

<b-button-group class="page-buttons mt-2" size="sm">
   <b-button v-for="btn in buttons" 
      :key="btn.key" 
      @click="selectPage(btn.key)"
      v-bind:class="{'active': btn.active}">{{ btn.caption }}
   </b-button>
 </b-button-group>

Script:

methods: {
    $createPaginationButtons: function(numberParameters) {
      const numberPages = Math.ceil(numberParameters / NUMBER_ELEMENT_PER_PAGE);
      this.buttons = [];

      for (let i = 0; i < numberPages; i++) {
        this.buttons.push({
          caption: `PAGE ${i + 1}`,
          active: (i === 0),
          key: (i + 1)
        });
      }

      Vue.set(this.buttons[0], 'active', true);
   }
}

The buttons array is initialize in data as an empty array. when my buttons array changes, the view is updated and display the correct number of buttons but my class active is not triggered.

Have you any idea.

Upvotes: 1

Views: 762

Answers (1)

Push is a wrapped method so it will trigger a view update.

Do you have declared buttons on the data property?

data() {
     buttons:[]
}

Since you are creating the active property as i === 0 you don't need Vue.set.

I don't know if has something to do but instead of making buttons empty and then pushing, use an aux variable to create the array and then just do this.buttons = auxVariable. This should trigger an update.

Upvotes: 1

Related Questions