1. 程式人生 > 其它 >uniapp store模組化開發

uniapp store模組化開發

技術標籤:uniapp電商app開發vue.js

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)
	}
}