
export default new Vuex.Store({ state: { city:"武汉" }, //简单的状态逻辑写在mutations中 mutations: { //可以更改状态 }, //复杂的业务逻辑写在actions中,异步操作方法这里 actions: { //异步提交更改 }})
//main.jsnew Vue({ store // 会在所有的组件上挂载一个$store属性})
一 正常的工作流
<template> <div> <button @click="changeCity(item)" v-for="(item,index) of citys" :key="index">{{item}}</button> </div></template><script>export default { data(){ return { citys:["武汉","杭州","厦门"] } }, methods:{ changeCity(city){ console.log(city) // console.log(this) this.$store.dispatch("changeCity",city); } }};</script>
//vuex
export default new Vuex.Store({
state: {
city:"武汉"
},
mutations: {
changeStateCity(state,val){
console.log(val)
state.city = val
}
},
actions: {
changeCity(ctx,val){
ctx.commit("changeStateCity",val)
}
},
modules: {
}
})