在uniapp中使用vuex

新建store

首先我们需要新建store文件夹,在文件夹下新建index.js文件,存放vuex核心代码:

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {// 用来缓存数据
	},
	mutations: { // 事件
	}
})

export default store

然后需要在根目录下的main.js文件中进行挂载,方便全局使用:

import store from './store/index.js'
Vue.prototype.$store = store

这样一来在项目中使用vuex的基础配置就完成了,剩下就是进行相应的使用操作

模拟登录案例

下面我们使用vuex在uniapp中实现一个模拟登录的案例,主要就是在store中进行变量的读取与更改:

首先我们先在state中定义我们需要的变量:
./store/index.js:
state中定义数据,mutations中定义改变登录值的函数

import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {// 用来缓存数据
		name: 'jack',
		isLogin: false,   //判断是否已登录
	},
	mutations: {
		// 改变isLogin的值
		setLogin(state, payload) {
			state.isLogin  = payload;
		}
	}
})
export default store

然后开始写登录页面:
在计算属性中通过mapState拿到store中state的值,然后编写登录和注销的函数进行相关的操作
因为已经将store全局挂载,所以直接可以使用this.$store.commit读取到mutations中的函数

<template>
	<view class="login">
		<view>
			登录状态: {{isLogin}}
		</view>
		<button type="default" @click="login">登录</button>
		<button type="default" @click="logout">注销</button>
		<navigator url="../index/index">首页</navigator>
	</view>
</template>

<script>
	import {mapState} from 'vuex'
	export default {
		computed: {
			...mapState(['name','isLogin'])
		},
		methods: {
			// 登录
			login() {
				this.$store.commit('setLogin', true);
			},
			// 登出 注销
			logout() {
				this.$store.commit('setLogin', false);
			}
		}
	}
</script>

这里的逻辑是:如果是登录状态,则可以正常点击首页进行跳转,否则点击首页无法跳转
所以我们需要在首页进行检查登录的状态:
主要是在onload和onshow生命周期函数中进行登录状态的检查,如果没有登录则跳回原登录界面

<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
			<text>{{name}}</text>
			<text>{{isLogin}}</text>
		</view>
	</view>
</template>

<script>
	import {mapState} from 'vuex'
	export default {
		data() {
			return {
				title: 'Hello'
			}
		},
		onLoad() {
			this.checkLogin();
		},
		onShow() {
			this.checkLogin();
		},
		computed: {
			...mapState(['name','isLogin'])
		},
		methods: {
			checkLogin() {
				if (!this.$store.state.isLogin) {
					uni.navigateTo({
						url:"../login/login"
					})
				}
			}
		}
	}
</script>

实现效果:

  1. 登录状态的切换

2.验证登录状态跳转页面

uniapp vue3 设置和使用globalData_模拟登录