先看场景

三个页面: 支付页、支付结果页、外部广告页
前些天开发中遇到支付页支付后,传递支付成功状态至结果页,在结果页点击下方的广告图跳转至外部链接后返回,结果页显示支付失败。
“额,我不是支付成功了嘛,怎么又显示支付失败?excuse me?”

用户看到这,就会很迷惑,由于业务要求统一在结果页添加广告位,导致其他结果页也会遇到这种问题。

这时vuex就派上用场了。

看效果

未存储状态前,状态为支付成功,点击广告返回后,状态就丢失了
在这里插入图片描述
使用vuex后,点击广告返回后,支付成功的状态依然在
在这里插入图片描述

步骤
1 安装

npm install vuex

2 新建store
  • 在src目录下新建一个store/index.js
	import Vue from 'vue'
	import Vuex from 'vuex'
	Vue.use(Vuex)
	export default new Vuex.Store({
	  state: {},  // 存放数据
	  mutations: {},  // 对数据进行修改
	})
  • 在main.js中引入
	import Vue from 'vue'
	import store from './store'
	Vue.config.productionTip = false
	new Vue({
		el: '#app',
		router,
		store,
		components: { App },
		template: '<App/>'
	})

这个时候在页面打印this.$store就能看到store中的东西

3 存储和读取
  • 先在store/index.js中定义需要存储的数据和相关的函数方法
	  state: {
	    objInfo: {} // 存储的数据
	  },
	  mutations: {
	    // 定义的方法
	    setMsg (state, objInfo) {
	      state.objInfo = objInfo
	    }
	  }
  • 数据存储
	// 1 页面引入mapMutations
	import { mapMutations } from 'vuex';
	
	// 2 在methods周期引入mapMutations里用到的方法
	 ...mapMutations(['setMsg']),
	 
 	// 3 在需要存储数据的地方调用该方法,此处存储isSuccess和errorMsg
 	this.setMsg({isSuccess: true, errorMsg: '支付失败'})
  • 现在在store中就能看到刚存进去的数据了,接下来在需要的页面进行读取
	// 1 页面引入mapState
	import { mapState } from 'vuex';
	// 2 computeds周期引入mapState需要用到的变量或模块名
	computed: {
		...mapState(['objInfo'])
	},
	// 3 在需要用的地方直接this.变量名
	console.log(this.objInfo);
4 持久化存储

历经千辛万苦,终于把数据存进去和读出来了,但运行会发现有bug,一刷新页面,我这数据又不见了,这不和我直接在router跳转时传数据的效果一样嘛,不能持久化,还是实现不了想要的效果。

是因为vuex本质上是一个公共变量,存储于浏览器内存中,刷新页面,浏览器内存重置,清空数据。那就需要我们再做一些操作来实现持久化存储。

vue-persist插件上场

  • 先安装npm install vue-persist -D
  • store/index.js中引入
	import VuexPersist from 'vuex-persist';
	// 创建对象,借助浏览器缓存,存入localStorage
	const vuexLocal = new VuexPersist({
	  	storage: window.localStorage  // 可选,sessionStorage/indexDB
	})
	// 引入该插件
	export default new Vuex.Store({
		state: {},
		mutations: {},
		plugins: [vuexLocal.plugin]
	})

再运行,就ok了,成功实现想要的效果。

后面的话

当页面存储的数据存在于多个模块时,可使用模块来切分store,在store下新建模块存储对应的数据。

Logo

前往低代码交流专区

更多推荐