Celso
Celso

Reputation: 127

Vuejs component doesn't update when changing variable

I'm learning Vue.js and have been able to write a simple list/detail application. Selecting the first item renders the detail component with the correct data, however when I select a different item the detail component doesn't reload with the right information.

For example:

<template>
<div>
    <detail :obj="currentObject"></detail>
</div>
</template>
<script>
export default: {
  data: function(){
    return {
      currentObject: null,
      objs = [
        {name:'obj 1'},
        {name:'obj 2'}
      ]
   };
  }
}
</script>

When I do this.currentObject = objs[0] the component detail updates with the correct content. However the next time I call this.currentObject = objs[1], the component detail no longer updates.

Upvotes: 2

Views: 1925

Answers (1)

calmar
calmar

Reputation: 1959

Not sure what's the context your are switching the data on your currentObject, but the below is a concept detail component and when you switch the objs it updated the prop :obj and seems working fine.

Looking at your code, you should declare objs using : not =.

data: function() {
    return {
      currentObject: null,
      objs: [
        {name:'obj 1'},
        {name:'obj 2'}
      ]
   };
 }

Here is the concept detail component, run the snippet to check it working.

Vue.component('detail', {
  props: ['obj'],
  template: '<div>{{ obj }}</div>'
})

var app = new Vue({
  el: '#app',
  data() {
    return {
      bToggle: false,
      currentObject: null,
      objs: [
        {name:'obj 1'},
        {name:'obj 2'}
      ]
    }
   },
   created(){
    this.switchData();
   },
   methods: {
    switchData() {
      if(!this.bToggle){
        this.currentObject = this.objs[0];
      }else{
        this.currentObject = this.objs[1];
      }
      this.bToggle = !this.bToggle;
   }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
    <button @click="switchData()"> switch </button>
    <detail :obj="currentObject"></detail>
</div>

Upvotes: 5

Related Questions