在 Vuex 中,使用 dispatch 触发 mutations 更改状态数据。使用 dispatch 存储一个值:this.$store.dispatch(‘setValue’, 10);使用 getters 从状态派生数据:getters: {
getValue: (state) => { return state.value; }
}在组件中使用 mapGetters 访问 getter:computed: {
…mapGetters({ value: ‘getValu
在 Vue 中使用 dispatch 存储值并获取
在 Vuex 状态管理中,dispatch 方法用于触发 mutations。这些 mutations 可以更改存储在 Vuex 状态中的数据。
要使用 dispatch 存储一个值,可以将值作为 mutation 的参数传递。例如:
this.$store.dispatch('setValue', 10);
登录后复制
在此示例中,setValue 是一个指定的 mutation,用于将值 10 存储在 Vuex 状态中。
要获取存储的值,可以使用 getters。getters 是从 Vuex 状态派生的计算属性,使你可以访问和操作状态数据。
要创建 getter,可以在 Vuex 模块中使用 getters 选项:
getters: { getValue: (state) => { return state.value; } }
登录后复制
然后,可以在组件中使用 mapGetters 助手函数来访问 getter:
computed: { ...mapGetters({ value: 'getValue', }), }
登录后复制
现在,你可以在组件中使用 this.value 访问存储的值。
完整示例:
// Vuex 模块 const module = { state: { value: null, }, mutations: { setValue(state, value) { state.value = value; }, }, getters: { getValue: (state) => { return state.value; } } }; // Vue 组件 export default { computed: { ...mapGetters({ value: 'getValue', }), }, methods: { setValue() { this.$store.dispatch('setValue', 10); }, }, };
登录后复制
以上就是vue中dispatch存值怎么取的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:牧草,转转请注明出处:https://www.dingdanghao.com/article/458432.html