29--store.js vuex状态管理模式

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
但是,当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:
多个视图依赖于同一状态。
来自不同视图的行为需要变更同一状态。比如token,登录后共享token,改变haslogin登录状态。

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		hasLogin: false,
		token: '',
		myinfo: {},
		unitid:''
	},
	mutations: {
		// 登录成功
		login: function(state, token) {
			state.hasLogin = true
			state.token = token
		},
		// setToken:function(state,token){
		// 	state.token =token
		// },
		// 保存个人信息,obj是一个对象
		setMyinfo: function(state, obj) {
			// 合并对象 两种
			// state.myinfo = { ...state.myinfo,
			// 	...obj
			// }
			state.myinfo=Object.assign({},state.myinfo,obj)
		},
		// 退出
		logout:function(state){
			state.hasLogin = false
			state.token=''
			state.myinfo={}
		}
	}
})
export default store

main.js
为了在 Vue 组件中访问 this.$store property,你需要为 Vue 实例提供创建好的 store

import Vue from 'vue'
import App from './App'
import store from './store/index.js'
Vue.config.productionTip = false
Vue.prototype.$store = store
App.mpType = 'app'
const app = new Vue({
	store,
	...App
})
app.$mount()

可以通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:

computed: {
	hasLogin: function() {
		return this.$store.state.hasLogin
	},
	myinfo: function() {
		return this.$store.state.myinfo
	}
},
this.$store.commit('login', res.data.token)
this.$store.commit('setMyInfo', res.data.myinfo)
login() {
	if (this.hasLogin == false) {
		uni.navigateTo({
			url: '/pages/index/login'
		})
	}
},

提示未登录

		onShow: function() {
			if (this.hasLogin == false) {
				uni.showModal({
					title: "提示",
					content: "您还未登录,请先登录",
					confirmText: "登录",
					success: res => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/index/login'
							})
						}
					}
				})
				return
			}
			if (this.trainerid == undefined || this.trainerid == 0 || this.trainerid == '') {
				toast('您还没有排班', false)
			} else {
				this.fetchdata()
			}
		},

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。我们通过提交 mutation 的方式,而非直接改变 store.state.count,是因为我们想要更明确地追踪到状态的变化。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类在这里插入图片描述
Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。
你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 increment 的 mutation 时,调用此函数。”要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法。
在大多数情况下,载荷应该是一个对象
提交 mutation 的另一种方式是直接使用包含 type 属性的对象…

猜你喜欢

转载自blog.csdn.net/xu_ze_qin/article/details/107772624