
异步操作放在actions里面 或者说是 批量的同步操作也放在actions里面
actions需要用commit来调用mutation
cnpm install vuex --save
创建store目录并在store目录下创建index.js
在main.js入口文件中引入,加入store
export default new Vuex.Store({
state:{
city : "天下"
},
actions:{
changeCity(ctx,city){
ctx.commit('changeCity',city)
}
},
mutations:{
changeCity(state,city){
state.city = city
}
},
})
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
获取state的值
{{this.$store.state.city}}
state语法糖
import {mapState} from 'vuex'
computed:{
...mapState(['city'])
}
调用actions
this.$store.dispatch('changeCity',city)
若没有actions的话直接使用commit来调用mutations
this.$store.commit('changeCity',city)
本文介绍如何使用Vuex进行状态管理,包括创建store、定义state、mutations和actions,以及如何在Vue项目中引入并使用store。同时讲解了通过actions进行异步操作的方法。


被折叠的 条评论
为什么被折叠?



