uniapp的store使用

 

store模块化开发

 

首先是文档结构:
store文件夹默认的文件是index.js,这个文件相当于主入口文件:

store中Index.js文件内容如下:

import Vue from "vue"
import Vuex from "vuex"
import cart from "./modules/cart.js"
import shop from "./modules/shop.js"

Vue.use(Vuex)
const store = new Vuex.Store({
    state:{
        hasLogin:false,
        userInfo:{},
        token:"',
        openId:"",
        path:"xxxxxx",
        registerUrl:"xxxxxxxx"
    },
    getters:{
        getOpenId(state){
            return state.openId
        }
    },
    mutations:{
        setToken(state,payload){
            state.token = payload;
        }
    },
    actions:{
        getData({commit},payload){
            commit("setToken",payload)
        }
    },
    modules:{
        cart,
        shop
    }
})
export default store

modules下的cart.js文件

const state = {
    updateCart:true,
    cartCount:0
}
const getters = {
    getUpdateCart(state){
        return state.updateCart
    }
}
const mutations = {
    setUpdateCart(state,flag){
        state.updateCart = Boolean(flag);
    }
}

export default{
    namespaced:true,
    state,
    getters,
    mutations,
    actions
}

这个文件还可以写成下面的方式:

import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const store = new Vuex.Store({
    state:{
        updateCart:true,
        cartCount:0
    },
    getters:{
        getUpdateCart(state){
            return state.updateCart
        }
    },
    mutations:{
        setUpdateCart(state,payload){
            state.updateCart = Boolean(payload)
        }
    },
    actions:{
    }
})
export default{
    namespaced:true,
    store
}

调用modules中的函数方法

this.$store.commit("cart/setUpdateCart",true)

调用函数的时候需要把模块的名称也加入到路径中,这样才可以调用到对应的函数。

main.js文件内容

import Vue from "vue"
import store from "./store"
import App from "./App"
import request from "utils/request.js"

import * as filters from "@/utils/filters"
import {msg} from "@/utils/index.js"

Vue.use(userLogin)
Vue.prototype.$store = store; 这样就可以使用this.$store.state来调用store中的数据了
Vue.prototype.$request = request

const add = new Vue({
    ...App
}).$mount()

export default app

request.js文件内容

import store from "./store";
import vue from "./main.js";
import {API_BASE_URL} from "@/common/config.js";
var lasttime = 0;
var nowtime = 0;
var auth = false;
var timeId = null;

function urlRequest(url,param,way,res,callBack){
    uni.getNetworkType({
        success:function(res){
            if(res.networkType==='none'){
                uni.navigateTo({
                    url:"/pages/public/noWifi"
                })
                return
            }
        }
    })
    let d = new Date();
    let dval = 0;
    let addVal = 0;
    if(nowtime){
        dval = d.getTime() - nowtime;
        if(dval < 500){
            addVal += dval;
        }
    }
    if(!param.isWait && (dval > 1000 || addVal === 0)){
        console.log("加载一次");
    }
    nowtime = d.getTime();//获取点击时间
    let token = uni.getStorageSync('token') || "";
    let openId = uni.getStorageSync("openId");
    let dataParam = way=='POST'?JSON.stringify(Object.assign(param)):param;
    let conType = "application/json";
    if(param.contype == 'form'){
        dataParam = param;
        conType = "appliccation/x-www-form-urlencoded"
    }
    console.log("返回的openId",openId);
    uni.request({
        url:API_BASE_URL+url,
        data:dataParam,
        header:{
            "ak":token,
            "dk":dk,
            "pk":"wbm",
            "pt":"web",
            "Accept":"application/json",
            "Content-Type":conType
        },
        method:way,
        success:(data)=>{
            setTimeout(()=>{
                uni.hideLoading();
            },1500+addVal)
            if(data.data.code===200){
                res(data.data)
            }else{
                if(data.data.code===401){
                    console.log("接口出现401,跳转登录页面path:"+url);
                    let routes = getCurrentPages();
                    let curRoute = routes[routes.length - 1]
                    if(curRoute&&curRoute.route&&(curRoute.route ==='pages/public/login')){
                        return false
                    }
                    clearTimeOut(timeId);
                    timeId = setTimeout(()=>{
                        console.log("更新用户token");
                        userAuth();
                    },300)
                }
            }else{
                successWhite.map(WhiteUrl=>{
                    if(url===WhiteUrl){
                        res(data.data)
                    }
                })
                if(data.status){
                    uni.showToast({
                        title:data.message,
                        icon:"none",
                        duration:4000
                    })
                    return;
                }
                uni.showToast({
                    title:data.data.msg,
                    icon:"none",
                    duration:4000
                })
            }
        }
    },
    fail(data){
        if(callBack&&callBack.fail){
            callBack.fail(data);
        }
        setTimeout(()=>{
            uni.hideLoading();
        },300+addVal)
        setTimeout(()=>{
            uni.showToast({
                title:"数据加载异常",
                icon:"none",
                duration:1500
            })
        },4000)
    },
    complete:()=>{
        if(callBack&&callBack.complete){
            callBack.complete();
        }
        if(lasttime=nowtime){
            setTimeout(function(){
                uni.hideLoading();
            },600)
        }
    }
)    
}
funtion userAuth(token,openId){
    uni.login({
        provider:'weixin',
        success:function(loginRes){
            if(loginRes.code){
                userLogon:result=>{
                    const openid = result.openid
                    const unionId = result.unionId
                    if(!openid){
                        this.$api.msg('数据异常,无法进入登录页面')
                        console.log('openid空,无法进入登录页面',result);
                        setTimeout(()=>{
                            uni.switchTab({
                                url:"/pages/index/index"
                            })
                        },3000)
                        return false
                    }
                    uni.redirectTo({
                        url:"/pages/public/login?openId=${unionId}"
                    })
                }
            }
        }else{
            console.log("400获取code失败",loginRes);
        }
    })
}
export default{
    urlRequest:function(url,param,way,res,callBack){
        return urlRequest(url,param,way,res,callBack)
    }
}

 

 

 

 

转 : https://blog.csdn.net/yehaocheng520/article/details/112978466

https://blog.csdn.net/weixin_50114203/article/details/119889457

https://blog.csdn.net/moshark/article/details/106196823

posted @ 2021-12-28 21:18  与f  阅读(4667)  评论(0编辑  收藏  举报