8

I am still new to Vue and struggle with having a component update its contents as soon as connected data has been updated. The component will show the changed content as soon as it has been re-rendered though.

Component

Vue.component('report-summary', {
  props: ['translation', 'store'],
  watch: {
    'store.state.currentModel.Definition': {
      handler: function(change) {
        console.log('Change detected', change);
      },
      deep:true
    }
  },
  template: '<div>
    '<div class="alert alert-secondary" role="alert">' +
    '<h5 class="border-bottom border-dark"> {{ translation.currently_defined }}</h5>' +
    '<div>{{ store.state.currentModel.Definition.length }} {{translation.elements }}</div>' +
    '</div>' +
    '</div>'
});

store is passed in as a property in the HTML of the page:

<report-summary :translation="t" :store="store"></report-summary>

store itself is a Vuex.Store:

let store = new Vuex.Store({
  state: {
    t: undefined,
    currentModel: undefined
  },
  mutations: {
    storeNewModel(state) {
      let model = CloneFactory.sealedClone(
        window.Project.Model.ReportTemplateModel);
      model.Header = CloneFactory.sealedClone(
        window.Project.Model.ReportTemplateHeaderModel);
      state.currentModel = model;
    },
    storeNewModelDefinition(state, definition) {
     state.currentModel.Definition.push(definition);
    }
  }
});

The currentModel element gets initialized by invoking store.commit('storeNewModel'); before any data is stored in the model's Definition attribute.

The definition's content gets updated by using store.commit('storeNewModelDefinition') in a loop:

for (let c in this.$data.currentDefinition.charts) {
  store.commit('storeNewModelDefinition', c);
}

When store.commit('storeNewModelDefinition', c); is called the store updates as expected:

Vuex%20Store|325x190

But the component won't react to the changed data:

Not%20updated|553x110

Then when I navigate away (by changing the view which hides the embedded component) and again navigate to the view the content got updated:

updated|476x112

In the Console window I see that the watcher hasn't been triggered at any point in time:

console|681x133

What am I missing here? Thanks a lot for opening my eyes in advance.

Using an EventBus

Switching the watch to an event bus listener also didn't work as planned.

This is the initialization of the EventBus:

window.eventBus= new Vue(); 

I added this to my Component:

  created: function() {
    window.eventBus.$on('report-summary-update', function() {
      this.$nextTick(function(){ this.$forceUpdate(); });
    });
  }

And emit the event after adding or removing elements from the list:

window.eventBus.$emit('report-summary-update');

When setting a breakpoint in the Debugger watching the this.$forceUpdate(); I see that it's also being called but the UI still will show the old content without any changes. I am really lost right now.


P.S. I cross-posted this on the Vue forum but as the community is rather small hope to receive some feedback here.

4
  • Just out of curiousity, any reason why you're not using vue-cli for this project?
    – fh0592x
    Nov 29, 2019 at 16:43
  • 1
    Is there a reason you are passing the Vuex store in as a property instead of accessing it globally?
    – MJ_Wales
    Nov 29, 2019 at 16:53
  • Has the object returned by CloneFactory.sealedClone(window.Project.Model.ReportTemplateModel); field Definition or are you creating it later ? Nov 29, 2019 at 17:10
  • As said before I haven't really had the chance to do much with Vue so the vue-cli is also something I haven't used yet. Will check that out for sure! @MJ_Wales I tried accessing the store inside the template via window.store... but got an error instead that said that 'window is undefined'. Regarding the ReportTemplateModel, yes, that contains a property "Defitinition" which is an empty array when just initialized.
    – SaschaM78
    Nov 29, 2019 at 17:36

3 Answers 3

2

Pushing data to a nested array always causes such issues where the component does not update.

Try adding a getter to your store and use that getter to get data from the store

let store = new Vuex.Store({
  state: {
    t: undefined,
    currentModel: undefined
  },
  mutations: {
    storeNewModel(state) {
      let model = CloneFactory.sealedClone(
        window.Project.Model.ReportTemplateModel);
      model.Header = CloneFactory.sealedClone(
        window.Project.Model.ReportTemplateHeaderModel);
      state.currentModel = model;
    },
    storeNewModelDefinition(state, definition) {
     state.currentModel.Definition.push(definition);
    }
  },
  getters:{
    definitions(state){
      return state.currentModel.Definition
    }
  }
});

In your component, you can add a computed prop that gets the data from store

Vue.component('report-summary', {
  props: ['translation', 'store'],
  computed: {
    definitions(){
     return store.getters.definitions
    }
  },
  template: '<div>
    '<div class="alert alert-secondary" role="alert">' +
    '<h5 class="border-bottom border-dark"> {{ translation.currently_defined }}</h5>' +
    '<div>{{ definitions.length }} {{translation.elements }}</div>' +
    '</div>' +
    '</div>'
});

UPDATE (30 Nov, 2019) If the above code still does not work, change your storeNewModelDefinition mutation to this:

storeNewModelDefinition(state, definition) {
     // Create a new copy of definitions
     let definitions = [...state.currentModel.Definition]

     // Push the new item
     definitions.push(definition)

     // Use `Vue.set` so that Vuejs reacts to the change
     Vue.set(state.currentModel, 'Definition', definitions);
    }
4
  • 1
    Just a typo, it should be definitions.length instead of definition.length (note the S)
    – favcau
    Nov 29, 2019 at 17:05
  • I gave it a try, the getter and computer property were called when the component was initialized but not after a refresh to its underlying data happened. Still a helpful example, thanks for that.
    – SaschaM78
    Nov 30, 2019 at 13:28
  • @SaschaM78 There was a typo in the definitions getter.currentMode was used instead of currentModel. I have fixed it now. I hope you fixed it in your code. If it's still not working, then, I suggest one more change. Please see my update in the answer Nov 30, 2019 at 13:57
  • Yes, I had seen this and had already changed it in my code. I will also test your updated code, thank you very much for your effort!
    – SaschaM78
    Nov 30, 2019 at 14:50
2

Just a note on your EventBus experiment (you should definitely try to fix the reactivity issue instead of trying tricks like $forceUpdate)

Reason why your experiment with EventBus didn't work is the use of anonymous function as an event handler. Take a look at this piece of code:

  methods: {
    onEvent() {
      console.log(this)
    }
  },
  mounted() {
    // this.onEvent is method where "this" is bound to current Vue instance
    this.$bus.$on("test", this.onEvent);
    // Handler is anonymous function - "this" refers to EventBus Vue instance
    this.$bus.$on("test", function() {
      console.log(this)
    });
  }
  • 1t event handler is a function where this is is explicitly (by Vue itself) bound to Vue instance where the handler "lives"
  • 2nd event handler is anonymous function, this is not explicitly bound so it ends up like this == event bus Vue instance. You can work around that using closure like this:
  mounted() {
    let self = this;
    this.$bus.$on("test", function() {
       // self = "this" in context of function "mounted"
       console.log(self)
    });
  }

this in JS can be tricky...

4
  • My old nemesis this. Yes, that perfectly makes sense that this does not refer to the Component in that case. I fixed my code to use the EventBus as shown in your example and now the Component gets updated as soon as the definition changes. I will still try to find a better way than to call $forceUpdate but for now it works like a charm. Thank you.
    – SaschaM78
    Nov 30, 2019 at 13:31
  • I disagree that event bus should be use to inform the component about changes in Vuex state. It's like using a gun to kill a mosquito. I request that this should not be marked as an accpeted answer as it could mislead upcoming developers in the community. Nov 30, 2019 at 13:59
  • Completely agree. This shouldn't be an accepted answer. I was just trying to explain the problem with event bus code.... Nov 30, 2019 at 14:15
  • Michal, @AnkitKante, this answer solved my problem right now, that's why I had checked it as a solution. I unchecked it now and will go forward with the update you provided in your answer to see if I can fix my problem in the correct way.
    – SaschaM78
    Dec 2, 2019 at 13:06
0

From vuejs documentation Reactivity in depth section

a property must be present in the data object in order for Vue to convert it and make it reactive

and this is one-off vue reactivity caveat. Vue cannot detect property addition or deletion.

in your state instead of currentModel: undefined add all properties you want to be reactive like

currentModel: { definitions:[] }

then any addition or removal of an element from definitions array would automatically become reactive.

And you can find more explanation on the documentation

Reactivity in depth

Change detection caveats

2
  • Thanks for your answer and the helpful links. I had already added an initial empty array definitions property in my tests but it still didn't fix the issue at that time (but it might be that I had additional issues in my code at that time that prevented it from working as expected).
    – SaschaM78
    Dec 2, 2019 at 13:02
  • Yes, adding new properties to objects already assigned to component data is problematic but if your component already has reactive property currentModel and you assign new object to it (as he did), whole object is made reactive. So its not important to define whole "shape" of your object in data. Your object just has to be "complete" (in regards to shape) before you assign it into existing data property.... Dec 7, 2019 at 17:59

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.