uni-app开发微信小程序使用vuex保存用户状态详细操作

  1. uniapp项目根目录下创建store文件夹并新建index.js文件
  2. 安装vuex并引入到该js文件
    npm install vuex --save
// index.js
	import Vue from 'vue'
	import Vuex from 'vuex'
	Vue.use(Vuex)

第二步 在该文件下创建实例对象并创建登录和登出的方法

const store = new Vuex.Store({
	state: {
		hasLogin : false,
		dataInfo : {},
	},
	mutations: {
		//  登录
		login(state,info){
			state.hasLogin = true;  // 调用了这个方法就是 true
			state.dataInfo = info; // 登陆状态为 true 表示已经登录	
			// 下次打开的时候判断是否有值,如果有就更新全局变量;
			uni.setStorageSync('dataInfo',state)
			console.log("成功登录")
		},
		// loginout 用户推出登陆后清除数据
		logout(state){
			state.hasLogin = false; // 修改登陆状态
			state.dataInfo = {};
			state.company_name = '';
			uni.clearStorageSync('dataInfo'); // 同步清除本地缓存
			console.log('退出登录')
		}
	}
})

export default store

第三部 需要去配置文件注册引入这个index.js
main.js里

	import Vue from 'vue'
	import App from './App'
	import store from './store'  

	Vue.prototype.$store = store

	Vue.config.productionTip = false
	
	App.mpType = 'app'
	
	const app = new Vue({
		store,
	    ...App
	})
app.$mount()

第四步 注册完实例之后需要在App.vue里面监听vuex的值是否有变化
(我们知道,vuex是全局管理状态的工具, 但是页面刷新vuex的数据就会清除)
所以
在页面跳转的时候都要经过一次app.vue 来重新赋值vuex
这里我们需要把在缓存里的数据重新赋值给vuex

<script>
	import {mapMutations} from 'vuex';
	export default {
		methods: {
			...mapMutations(['login'])
		},
		onLaunch: function() {
			if(uni.getStorageSync('dataInfo')){
				let userInfo  = uni.getStorageSync('dataInfo');
				this.login(userInfo.dataInfo)
			}
			console.log(this.$store.state)
		
		},
		onShow: function() {
			// console.log('App Show')
		},
		onHide: function() {
			// console.log('App Hide')
		}
	}
</script>

第五步 在需要检验登录状态的页面使用vuex

	import {mapState,mapMutations} from 'vuex'
	export default{
		data(){
			return{
				isLogin : false
			}
		},
		onLoad(){
			this._getStorageUser();
		},
		onShow(){
			this._getStorageUser();
		},
		methods: {
			...mapMutations(['login','logout']),
			// 用户退出登录
			comfrimExit : function(){
				this.logout();  //调用vuex的登出方法
				this.$refs.uTips.show({
					title: '操作成功',
					type: 'success',
					duration: '2300'
				})
				this.isLogin = false;
				this.userInfo = {};
			},	
			_getStorageUser : function(){
				if(uni.getStorageSync('dataInfo')){
					this.isLogin = true;
					let wechatInfo = uni.getStorageSync('dataInfo');
					this.userInfo = wechatInfo.dataInfo;
				}else{
					this.isLogin = false;
					this.userInfo = {};
				}
			},
			
			// 微信登陆
			_goWechatLogin : function(){
				uni.getUserProfile({
					desc : '登录',
					success : (res) => {
						this.isLogin = true;
						this.userInfo = res.userInfo;
						this.login(this.userInfo) // 把用户信息传给vuex保存
					},
					fail : (res) => {
						// console.log(this.$store.state.isLogin)
						console.log('登陆失败',res);
						uni.showToast({
							title: '您拒绝了微信授权,将无法使用部分功能!',
							icon :  'none',
							mask: true
						})
					}
				})
			}
		}
	}
</script>

至此大功告成

Logo

前往低代码交流专区

更多推荐