1.Vuex是一个仓库,仓库存储了应用的状态
Vuex有以下四个东西
1.state
2.getter
3.mutation
4.action
state就像组件中的data,我们把相关的数据存储在state中getter可以从state中得到新的数据集合
mutation 是唯一的修改state的入口,想要修改state我们必须使用mutation,
mutation是同步的,action是进行异步操作的地方(如请求数据)请求到的数据需要放到state中,我们需要在action请求数据之后,调用mutation对state进行修改。action是异步的
2.vuex使用
1.创建store实例
const store = new Vue,Store({
state: {
}
})
2. 把store添加到Vue实例中
当我们把store添加到vue中后,那么在每一个组件中都会自动多一个data 为$store
因此想要使用模板中的数据很简单
$store.state.属性
表达式过长时可以使用computed
使用Vuex之后,在任何一个组件中的data中都会有一个
store.state.xxx}}
在组件函数中:this.$store.state.xxx
所以为了好看可以写在computed中
computed: {
msg () {
return this.$store.state.msg
}
}