返回

细说Vuex源码,探索组件如何访问数据及触发状态更新

前端

Vuex是一个流行的、轻量级状态管理库,用于构建Vue.js应用程序。它允许你在应用程序中存储、共享和管理状态,并通过组件访问和修改状态。

组件如何访问Vuex注册的数据?

组件可以通过this.store.state访问Vuex注册的数据。this.store是一个特殊的属性,它是由Vuex自动添加到每个组件的。它指向Vuex的store实例,store实例是一个包含应用程序所有状态的对象。

例如,如果你在Vuex中注册了如下数据:

const store = new Vuex.Store({
  state: {
    count: 0
  }
})

那么你就可以在组件中通过如下方式访问count数据:

export default {
  template: `<div>{{ count }}</div>`,
  computed: {
    count() {
      return this.$store.state.count
    }
  }
}

组件如何触发相应的mutation来更新state?

组件可以通过this.$store.commit()触发相应的mutation来更新state。mutation是一个函数,它可以修改store中的state。

例如,如果你在Vuex中注册了如下mutation:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  }
})

那么你就可以在组件中通过如下方式触发increment mutation:

export default {
  template: `<button @click="increment">+</button>`,
  methods: {
    increment() {
      this.$store.commit('increment')
    }
  }
}

结论

通过本文,我们了解了组件是如何通过this.store.state访问Vuex注册的数据,以及如何通过this.store.commit()触发相应的mutation来更新state。希望这些知识能够帮助你在实际项目中更好地使用Vuex。