vuex 解决报错this.$store.commit is not a function的方法

2020-06-14 05:59:35易采站长站整理

return this.$store.state.bankInf.bankName;
}
},
...
}

在模板中可以直接使用bankName这个属性了,也就是store中的中国银行

【二、在组件中修改store中的状态 】

在任意组件中添加html模板


<div class="bank">
<list-header :headerData="bankName"></list-header>
04银行详情页面
<input name="" v-model="textValue">
<button type="button" name="获取数据" @click="newBankName"></button>
</div>

然后组件中提交mutation


export default {
...
computed: {
bankName() {
return this.$store.state.bankInf.bankName;
}
},
methods: {
newBankName: function() {
this.$store.commit('newBankName', this.textValue)
}
}
...
}

在store中的index.js中添加mutations:


const store = new Vuex.Store({
state: {
// 放置初始状态 app启动的时候的全局的初始值
bankInf: {"name":"我是vuex的第一个数据","id":100,"bankName":"中国银行"},
count:0
},
mutations: {
newBankName(state,msg) {
state.bankInf.bankName = msg;
}
}
})

这样你发现,在点击提交按钮的时候,页面已经显示你修改的数据了,并且所有复用这个组件的地方的数据全都被vue更新了;

如果在使用中发现报错this.$store.commit is not a function ,请打开你项目的配置文件package.json,查看你正在使用的vuex的版本,我正在使用的是vuex2.0,

如果想删除旧版本的vuex并安装新版本的vuex请使用


npm rm vuex --save

然后安装最新的vuex


npm install vuex --save

即可解决这个错误,或者是查看vuex官网api修改提交mutation的语句