Search code examples
javascriptvue.jsvue-componentvuexnuxt.js

How to Add new Property Object in State Vuex/Vue/Nuxt


i have a state, and i want put new property foo: 'bar' to detail state

export const state = () => ({
  detail: {a: 'b', c: 'd'}
})

export const mutations = {
  SET (state, data) {
    state.detail.foo = 'bar'
  }
}

and i show the state in html

<template>
  <div>{{ data}}</div>
  /* {a: 'b', c: 'd'} */
</template>
<script>
..
  computed: {
    ...mapState({
      data: state => state.detail
    })
  },
..
</script>

the data is showing {a: 'b', c: 'd'}, but when i click the button to add foo: 'bar' the state will changed, but not refresh in html. i mush F5(refresh the browser) to show the new data foo: 'bar'


Solution

  • Import vue in your store code then use Vue.set(state.detail,"foo" , 'bar')

    import Vue from 'vue'
    ....
    
    export const mutations = {
      SET (state, data) {
       Vue.set(state.detail,"foo" , 'bar')
      }
    }