方法:1、項(xiàng)目根目錄下新建store目錄,該目錄里創(chuàng)建“index.js”文件;2、“index.js”下引入vue和vuex;3、“main.js”中掛載Vuex;4、在“pages/index/index.vue”中使用vuex即可。
本教程操作環(huán)境:windows7系統(tǒng)、vue2.9.6&&uni-app2.5.1版,DELL G3電腦。
uni-app中使用vuex的方法:
在uni-app中內(nèi)置了vuex,我們只需要引用就行了
1、在 uni-app 項(xiàng)目根目錄下新建 store 目錄,在 store 目錄下創(chuàng)建 index.js
2、新建的index.js下引入vue和vuex,具體如下:
//引入vue和vuex import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({//全局變量定義 state: { forcedLogin: false,//是否需要強(qiáng)制登錄 hasLogin: false, userName: "", userId:'', token:'', pointId:'', }, mutations: { login(state, user) { state.userName = user.username || ''; state.hasLogin = true; state.userId = user.id || ''; state.token = user.token || ''; state.pointId = user.pointId || ''; }, logout(state) { state.userName = ""; state.hasLogin = false; state.userId = ''; state.token = ''; state.pointId = ''; } } }) export default store
3、需要在 main.js 掛載 Vuex
import store from './store' Vue.prototype.$store = store
想要定義的這個(gè) js 文件中的變量和方法能在各個(gè)頁面使用并生效,需要先在項(xiàng)目目錄下的 main.js 文件中導(dǎo)入這個(gè) js 文件并聲明方法,如下圖所示:
4、在 pages/index/index.vue 使用
-
先在頁面導(dǎo)入vuex的方法
-
然后,在 computed 計(jì)算屬性方法中使用 mapState 對(duì)全局變量進(jìn)行監(jiān)控。
-
一進(jìn)來index.vue 頁面,在onload()頁面加載的時(shí)候,判斷是否已是登陸狀態(tài),不是的話,彈出對(duì)話框,提示進(jìn)行‘登陸操作’
登陸頁面
-
先在頁面導(dǎo)入vuex的方法,如下:
-
在 computed 計(jì)算屬性方法中使用 mapState 對(duì)全局變量進(jìn)行監(jiān)控,在 method中使用 mapMutations 進(jìn)行全局方法監(jiān)控,如下所示:
-
網(wǎng)絡(luò)請(qǐng)求成功后,在回調(diào)函數(shù) success 中調(diào)用該方法,并把回調(diào)函數(shù)的返回值數(shù)據(jù)傳給 login 方法
-
隨后 store/ index.js 文件中的login方法會(huì)把傳過來的用戶數(shù)據(jù)保存在vuex。
擴(kuò)展
在vue文件中使用 取值,比如其中的token,可以使用‘this.$store.state.token’這樣來取。
在js文件中使用
1、import store from '../../store' 先引用
2、store.state.token 取值