vue.js - Vue / Vuex:计算内部的mapState未更新
问题描述
我正在尝试利用mapState
反应性数据并遇到问题。我的Test.vue
组件中有以下内容
<template>
<div> {{ name }} </div>
</template>
computed: {
...mapState('user', ['age','name]
}
当我的状态user.name
在组件之外更新时Test.vue
,新值不会显示在里面Test.vue
。
例如,如果我通过我的突变进行更新userStore
,
[SET_USER_NAME_MUTATION](state, value) {
state.name = value;
},
commit('SET_USER_NAME_MUTATION', "John")
当我检查 chrome DevTools 时,现在在我的 Vuex 商店中user { name: "John" }
,这是正确的
解决方案
您应该通过 vuex 操作来改变状态,而不是直接调用突变。尝试这样的事情,假设您的状态包含一个user
具有name
属性的对象:
Vue 组件
<template>
<div>
<span>{{ name }}</span>
<button @click="changeName">Change name</button>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'MyComponent',
computed: {
...mapState({
name: state => state.user.name
})
},
methods: {
changeName () {
this.$store.dispatch('changeName', 'John Smith')
}
}
}
</script>
Vuex商店
// state
const state = {
user: {
name: null
}
}
// getters
const getters = {
// ...
}
// actions
const actions = {
changeName ({ commit }, payload) {
commit('setName', payload)
}
}
// mutations
const mutations = {
setName (state, payload) {
state.user.name = payload
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
无论如何,根据您的具体情况了解您的状态结构以更好的方法将非常有帮助
推荐阅读
- mysql - 需要增强过滤器的 MYSQL 数据透视表
- java - 在没有任何价值的情况下使用 CDI @Named CDI 有什么意义吗?
- function - Flutter 函数调用未按预期工作。(几乎可以肯定是语法错误)
- unity3d - 在一个动画中为两个类人动物制作动画
- http - Golang RoundTripper 提供空回复
- xamarin.forms - 适用于 iOS 和 Android 的蓝牙扫描仪(Xamarin Forms)
- html - 如何使用 webpack 在网站的浏览器选项卡中放置图标(favicon)?
- google-apps-script - Google Script 有时无法读取完整的电子表格
- scroll - 大型 Org 模式文件和 org-do-latex-and-related 函数中的缓慢光标移动
- visual-studio - .sqlproj 文件的版本控制