vuex介绍及使用指南(面向实战)
目录
什么是vuex?
编写vuex代码
1.首先要确保你下载了vuex,具体怎么判断请自行参考文档
2.先看文档结构
3.index.js代码
4.modules文件中的代码
四个属性的解释
全局挂载
使用方法:
state:
getter:
Mutations与Actions:
具体案例代码如下:
什么是vuex?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
简单理解:vuex就是存放公共数据,并对公共数据进行操作的一种技术。
编写vuex代码
1.首先要确保你下载了vuex,具体怎么判断请自行参考文档
2.先看文档结构
3.index.js代码
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
//这里引入三个modules文件,这三个是我的项目需要,读者可以只设置一个,那么相应的
//仅需进入一个js文件,export default也写入一个即可
import user from "@/store/modules/user.js"
import bleList from "@/store/modules/bleList.js"
import netList from "@/store/modules/netList.js"export default new Vuex.Store({modules:{user,bleList,netList}
})
4.modules文件中的代码
export default{//可以理解为data数据state:{//用户登陆状态loginStatus:false,//用户tokentoken:null,//用户信息userInfo:{} },//可以理解为计算属性getters:{},//同步方法(一般用于修改state)mutations:{//初始化登陆状态initUser(state){let userInfo=uni.getStorageSync("userInfo")if(userInfo){userInfo=JSON.parse(userInfo)state.userInfo=userInfostate.token=userInfo.tokenstate.loginStatus=true}},//登录login(state,userInfo){state.userInfo=userInfostate.token=userInfo.tokenstate.loginStatus=true//持久化存储uni.setStorageSync("userInfo",JSON.stringify(userInfo))},//退出登录logout(state){state.loginStatus=falsestate.token=nullstate.userInfo={}//清除存储uni.removeStorageSync("userInfo")}},//异步方法actions:{},}
四个属性的解释
state:可以理解为正常vue界面的data
getters:可以理解为正常界面的compute属性
mutations:同步方法,方法中必须有state,可参考笔者函数
actions:异步方法,可以进行数据库访问等。
备注:很多人分不清mutations和actions什么时候用,笔者提供一种简单判断方法。只要设置state修改,则使用mutations,但如果要访问服务器,则用actions。即mutations优先修改state,actions访问后端接口用
全局挂载
在main.js中全局挂载
下面这个图片是main.js中自己写的
下面这个图片是在mian.js中自己加上store,其余代码uniapp有自动生成
做好以上挂载配置,就可以使用啦!
使用方法:
state:
1、HTLM标签中使用时:
2、js中:
this.$store.state.全局数据名称
例如,如果使用笔者示例的token数据,则为this.$store.state.user.token
3、JS中(推荐):
先引入
import {mapState} from "vuex"
再在computed中解析数据
computed:{...mapState({netBattery:state=>state.netList.netBattery,//实时获取设备列表userInfo:state=>state.user.userInfo,//用户信息token:state=>state.user.token,//用户token})},
这里的数据,就可以认为是data数据,按照data中数据直接使用即可。在conputed中,就是因为如果别的页面改变了state中的值,那么此界面也可以立马对数据做出改变。
getter:
先引用
import {mapGetters} from "vuex"
再使用
computed: {...mapGetters(['checkedAll','totalPrice','disableSelectAll'])},
这里面的数据你也可以认为是data中数据,直接使用即可。
Mutations与Actions:
1、第一种方法:
先引用:
import {mapActions,mapMutations} from "vuex"
再使用
methods:{...mapActions(['doSelectAll','doDelGoods','doShowPopup','updateCartList']),...mapMutations(['selectItem','initCartList','unSelectAll']),}
这里的方法可以认为是methods里面的普通方法,直接调用即可。推荐使用这种方法,因为可以较直观看出使用的方法有哪些。
2、第二种方法:
使用commit触发Mutation函数,使用 dispatch触发Action函数
this.$store.commit("login")
this.$store.dispatch("allAdd")
具体案例代码如下:
注意:这里读者不用搞懂示例代码具体干了什么,仅需知道这些使用语法即可,可以作为vuex的使用参考。
import $H from '@/common/lib/request.js';
import $U from '@/common/lib/util.js';
export default {state:{list:[],// 选中列表(存放选中的id)selectedList:[],// popup显示popupShow:"none",popupIndex:-1,popupData:{}},getters:{// 判断是否全选checkedAll:(state)=>{return state.list.length === state.selectedList.length},// 合计totalPrice:(state)=>{var total = 0state.list.forEach(v=>{if (state.selectedList.indexOf(v.id) > -1) {total += v.pprice*v.num}})return total},// 禁用全选disableSelectAll:(state)=>{return state.list.length === 0},// 购物车商品数量cartCount:(state)=>{if(state.list.length <= 99){return state.list.length}return '99+'}},mutations:{// 初始化listinitCartList(state,list){state.list = list$U.updateCartBadge(state.list.length)},// 选中/取消选中某个商品selectItem(state,index){let id = state.list[index].idlet i = state.selectedList.indexOf(id)// 之前是选中,取消选中 if (i > -1) {// 取消当前商品选中状态state.list[index].checked = false// 移除选中列表中的当前商品return state.selectedList.splice(i,1)}// 选中state.list[index].checked = truestate.selectedList.push(id)},// 全选selectAll(state){state.selectedList = state.list.map(v=>{// 设置选中状态v.checked = truereturn v.id})},// 取消全选unSelectAll(state){state.list.forEach(v=>{// 设置选中状态v.checked = false})state.selectedList = []},// 删除选中delGoods(state){state.list = state.list.filter(v=>{return state.selectedList.indexOf(v.id) === -1})$U.updateCartBadge(state.list.length)},// 初始化popupIndexinitPopupIndex(state,index){state.popupIndex = index},// 加入购物车addGoodsToCart(state,goods){state.list.unshift(goods)$U.updateCartBadge(state.list.length)},// 清空购物车clearCart(state){state.list = []state.selectedList = []$U.updateCartBadge(state.list.length)}},actions:{// 更新购物车列表updateCartList({state,commit}){return new Promise((res,rej)=>{$H.get('/cart',{},{token:true,toast:false}).then(result=>{// 取消选中状态commit('unSelectAll')// 赋值commit('initCartList',result)res(result)}).catch(err=>{rej(err)})})},// 显示popupdoShowPopup({state,commit},{index,data}){commit('initPopupIndex',index)state.popupData = datastate.popupData.item = state.list[index]console.log(state.popupData);state.popupShow = 'show'},// 隐藏popupdoHidePopup({state,commit}){state.popupShow = 'hide'setTimeout(()=>{state.popupShow = 'none'commit('initPopupIndex',-1)},200)},doSelectAll({commit,getters}){getters.checkedAll ? commit('unSelectAll') : commit('selectAll')},doDelGoods({commit,state}){if(state.selectedList.length === 0){return uni.showToast({title: '请选择要删除的商品',icon: 'none'});}uni.showModal({content: '是否删除选中',success: (res)=>{if (res.confirm) {$H.post('/cart/delete',{shop_ids:state.selectedList.join(',')},{token:true}).then(res=>{commit('delGoods')commit('unSelectAll')uni.showToast({title: '删除成功'});})} }});}}
}
页面使用:
<template><view></view>
</template><script>import {mapState,mapGetters,mapActions,mapMutations} from "vuex"export default {data() {return {}},computed: {...mapState({list:state=>state.cart.list,selectedList:state=>state.cart.selectedList}),...mapGetters(['checkedAll','totalPrice','disableSelectAll'])},methods: {...mapActions(['doSelectAll','doDelGoods','doShowPopup','updateCartList']),...mapMutations(['selectItem','initCartList','unSelectAll'])}}
</script><style></style>
compute中数据当成data中数据看即可,actions与mutations中的方法按照methods中的普通方法看即可。