Vuex 的优点
数据仓库: 集中式存储
组件通信: 便于在各个组件之间进行数据共享、传递
单项数据流: 遵循特定的规则,特定的入口改变数据,特定的出口输出数据,
同时可监测到数据的变化过程
下载安装依赖
npm i vuex -s
Vuex的核心:state,mutation,action,getter,module
state 记录存储公共的状态。
mutation 事件改变state中的状态,第一个参数是state。
action 处理异步的事件。
getter 类似于计算属性
Vuex 的辅助函数
import {mapState,mapMutations,mapActions,mapGetters} from "vuex"
state的辅助函数需要映射到计算属性中computed,
映射的名称一定要相同,然后就可以通过this访问到state。
computed:{
...mapState(["name"]),//name和vuex中的state保持一至。
},
methods:{
click(){
console.log(this.name)//访问到vuex的name
}
}
mutation的辅助函数mapMutations把mutations里面的方法映射到methods中。
映射的名称一定要相同,然后就可以通过this调用mutaition的方法。
mutations: {
show(state){
console.log(state)
}
},
methods:{
...mapMutations(["show"]),
click(){
this.show()
},
}
mapAcions:把actions里面的方法映射到methods中
mapGetters:把getters属性映射到computed身上
Vuex 如何使用
建立一个store的文件夹,建一个index.js,在main.js里面全局引入,实例里面注册
index.js
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const mutations={
add(state,n){
state.num+=n
},
reduce(state,n){
// 可传参
state.num--
}
}
export default new Vuex.Store({
state:{
num:0,
arr:[]
},
// mutations 可以单独建立js 直接引入
mutations:{
add(state){
state.num++
},
reduce(state){
state.num--
}
},
// // mutations 异步分发
actions:{
addAction(context){
context.commit("add")
},
reduceAction({commit}){
commit("reduce")
}
},
getters:{
num(state){
return state.num
},
arr(state){
return state.arr
}
}
})
在组件中的使用
state
// state 获取值的方式
//第一种
// computed:{
// num(){
// return this.$store.state.num
// }
// }
// 第二种
// computed:{
// ...mapState(['num'])
// }
//第三种
// computed:mapState(['num'])
getter
// getters 获取值的方式
// 第一种
// computed:{
// num(){
// return this.$store.getters.num
// }
// },
// 第二种
// computed:{
// ...mapGetters(["num","arr"])
// },
//第三种
computed:mapGetters(["num"]),
// mutations 方法
mapMutations
// 第一种
// methods: {
// add() {
// this.$store.state.num++
// },
// reduce(){
// this.$store.state.num--
// }
// },
// 第二种
// methods: {
// ...mapMutations(["add","reduce"])
// },
// 第三种
// methods:mapMutations(["add","reduce"])
第四种
<button @click="$store.commit('add',5)">+</button>
<button @click="$store.commit('reduce',2)">-</button>
mapActions
//第一种方法
<button @click="$store.dispatch('addAction',5)">+</button>
<button @click="$store.dispatch('reduce',2)">-</button>
// 第二种方法
// methods:{
// ...mapActions(["addAction","reduceAction"])
// }
// 第三种方法
methods:mapActions(["addAction","reduceAction"]),