uni-app 使用Vuex+ (強制)登錄


一、在項目的根目錄下新建一個store文件夾,然后在文件夾下新建一個index.js文件

二、在新建的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,//是否需要強制登錄
        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

三、在main.js中注冊

想要定義的這個 js 文件中的變量和方法能在各個頁面使用並生效,需要先在項目目錄下的  main.js  文件中導入這個  js  文件並聲明方法,如下圖所示:

四、在 pages/index/index.vue 使用

1、先在頁面導入vuex的方法

2、然后,在 computed 計算屬性方法中使用  mapState 對全局變量進行監控。

3、一進來index.vue 頁面,在onload()頁面加載的時候,判斷是否已是登陸狀態,不是的話,彈出對話框,提示進行‘登陸操作’

 

 五、登陸頁面

1、先在頁面導入vuex的方法,如下:

2、在 computed 計算屬性方法中使用  mapState 對全局變量進行監控,在 method中使用  mapMutations  進行全局方法監控,如下所示:

3、網絡請求成功后,在回調函數 success 中調用該方法,並把回調函數的返回值數據傳給 login 方法

4、隨后 store/ index.js  文件中的login方法會把傳過來的用戶數據保存在vuex。

五、擴展

在vue文件中使用   取值,比如其中的token,可以使用‘this.$store.state.token’這樣來取。

在js文件中使用 

1、import store from '../../store' 先引用

2、store.state.token  取值 

vuex 中的 store 和 $store 的區別

$store 是掛載在 Vue 實例上的(即Vue.prototype),而組件也其實是一個Vue實例,在組件中可使用 this 訪問原型上的屬性,template 擁有組件實例的上下文,可直接通過  this.$store.state.token
store.state.token , 需聲明過 store 才可訪問。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM