1.什么是 vuex
vuex是一个状态管理工具,所谓状态就是数据。
vuex是一个插件,帮我们解决多组件共享数据的问题(例如:购物车,个人信息)
2. vuex 安装与使用
2.1 安装
npm install vuex@3
2.2 挂载与使用
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store()
export default store
2.3 初始化
const store = new Vuex.Store({
state:{
count:200
}
})
模版访问:
{{$store.state.count}}
组件里访问:
data() {
return {
bucuo:this.$store.state.count
}
}
3.修改vuex数据 mutaion
const store = new Vuex.Store({
state:{
count:200
},
mutations: {
// 第一个参数为 state
addcount(state,n) {
// 变更状态,即变更值
state.count+=n
}
}
})
组件:
this.$store.commit('addcount', 2)
4.异步修改数据 action
为什么不直接使用 mutations 因为它只支持同步,不支持异步操作。
action 是专门处理异步操作的
4.1 store 配置
异步修改count ,一秒后变成1000
const store = new Vuex.Store({
state:{
count:200
},
mutations: {
// 第一个参数为 state
addcount(state,n) {
// 变更状态,即变更值
state.count+=n
},
setcount(state,nums){
state.count=nums
}
},actions:{
setAsyncCount(context,num){
setTimeout(()=>{
context.commit('setcount',num);
},2000)
}
}
})
4.2 组件调用
<button @click="changes(1000)">变变变</button>
<script>
methods:{
changes(a){
this.$store.dispatch('setAsyncCount',a);
}
}
</script>
5关于助手函数 mapMutations 和 mapActions
mapMutations 和 mapState很像,它是把位于mutations中的方法提取了出来,映射到组件methods中。
这2个函数分别是映射 mutations 和 actions
具体用法:
vuex中的store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
userinfo:{},
cartnum:0
},
mutations: {
//set
setUserInfo(state,obj){
state.userinfo=obj
},
setCartnum(state,n){//修改购物车物品数量
state.cartnum+=n
},
setCartzero(state){//清空购物车
state.cartnum=0
}
},actions:{//异步
setAsynCartNum(context){
setTimeout(()=>{
context.commit('setCartzero')
},1000)
}
}
})
export default store
页面中去调用
<!--购物车-->
<div class="shop" @click="setCartnum(1);" >
<span >{{$store.state.cartnum}}
</span>
</div>
<!--清空购物车按钮-->
<div @click="setAsynCartNum" class="dogouwuche">1s清空购物车</div>
<script>
export default{
name:'HomeLay',
data() {
return {
lists:[]
}
},
methods:{
...mapMutations(['setCartnum']),
...mapActions(['setAsynCartNum'])
}
}
</script>