Skip to content

Instantly share code, notes, and snippets.

@BioBoost
Last active November 19, 2020 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BioBoost/3eda05866ac4154a56d67ff9673c9fae to your computer and use it in GitHub Desktop.
Save BioBoost/3eda05866ac4154a56d67ff9673c9fae to your computer and use it in GitHub Desktop.
Arrays and Reactivity in Vue

Source: https://stackoverflow.com/questions/51149729/updating-state-of-vuex-array-when-one-item-has-some-changes/51153076

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript" },
      { text: "Learn Vue" },
      { text: "Play around in JSFiddle" },
      { text: "Build something awesome" }
    ]
  },
  methods: {
    // work because object property is reactive
  	changeItemProperty() {
    	this.todos[3].text = "changedItemProperty";
    },
    // same reason, properties are reactive
    changeItemWithAssign() {
    	Object.assign(this.todos[3], { text: "changedItemWithAssign" });
    },
    // does not work, can not track changes in array
    // also this will break all attempts to change TEXT property in UI
    // because property becomes not reactive after this due to new object
    // try to changeItemProperty or  changeItemWithAssign - does not work!
    // changeItem2 will fix it :)
    changeItem() {
    	this.todos[3] = { text: "changedItem" }
    },
    // works
    changeItem2() {
    	Vue.set(this.todos, 3, { text: "changedItem2" });
    }	
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment