Vuex $store properties not reactive when using computed property

后端 未结 6 488
孤街浪徒
孤街浪徒 2020-12-29 23:03

I have a Vuex store, which I\'m injecting into my instance:

import store from \'../store\';

const mainNav = new Vue({
  el: \'#main-nav\',
  store,
  compon         


        
6条回答
  •  醉梦人生
    2020-12-29 23:04

    you should not manipulate store objects directly from component methods, you should commit mutations on store object. Mutations are functions that have listeners and when called changed variables are tracked and changes are propagated. If you need to do something async like submit data to the server you have to go even one step further define actions on the store, do async call and then commit mutations from there to update state object. I know this sounds so annoying but once you use to it it is pretty straight forward.

    const store = new Vuex.Store({
      state: {
        nav: {
          type: 'not wide by default'
        }
      },
      mutations: {
        changeType: (state, type) => {
          state.nav.type = type;
        }
      }
    })
    
    Vue.component('NavComponent', {
      template: '
    isWide?: {{isWide}}
    ', computed: { isWide () { return this.$store.state.nav.type === 'wide' } } }) new Vue({ el: '#app', store, methods: { changeType (type) { this.$store.commit('changeType', type); } } })
    
    
    

    https://codepen.io/zoransa/pen/KyqvWd?editors=1010

    it also works directly at stat.nav without type https://codepen.io/zoransa/pen/xPrLyW?editors=1010

提交回复
热议问题