uni-app 使用Vuex+ (强制)登陆

1、在项目的根目录下新建一个store文件夹,而后在文件夹下新建一个index.js文件vue

2、在新建的index.js下引入vue和vuex,具体以下: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

3、在main.js中注册segmentfault

想要定义的这个 js 文件中的变量和方法能在各个页面使用并生效,须要先在项目目录下的  main.js  文件中导入这个  js  文件并声明方法,以下图所示:网络

4、在 pages/index/index.vue 使用函数

一、先在页面导入vuex的方法post

二、而后,在 computed 计算属性方法中使用  mapState 对全局变量进行监控。this

三、一进来index.vue 页面,在onload()页面加载的时候,判断是否已经是登录状态,不是的话,弹出对话框,提示进行‘登录操做’spa

 

 5、登录页面prototype

一、先在页面导入vuex的方法,以下:code

二、在 computed 计算属性方法中使用  mapState 对全局变量进行监控,在 method中使用  mapMutations  进行全局方法监控,以下所示:

三、网络请求成功后,在回调函数 success 中调用该方法,并把回调函数的返回值数据传给 login 方法

四、随后 store/ index.js  文件中的login方法会把传过来的用户数据保存在vuex。

5、扩展

在vue文件中使用   取值,好比其中的token,可使用‘this.$store.state.token’这样来取。

在js文件中使用 

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

二、store.state.token  取值 

vuex 中的 store 和 $store 的区别

$store 是挂载在 Vue 实例上的(即Vue.prototype),而组件也实际上是一个Vue实例,在组件中可以使用 this 访问原型上的属性,template 拥有组件实例的上下文,可直接经过  this.$store.state.token
store.state.token , 需声明过 store 才可访问。

相关文章
相关标签/搜索