2

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.

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

1 Comment

This, although not the complete solution, pointed me in the right direction. Pretty much like @cal_br_mar mentioned, what I missed was a watch on the property obj so that when it changes some logic - that wasn't in the example - also runs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.