vue项目详解(3)-vuex的使用及常见的坑

本文介绍Vue.js应用程序的状态管理模式Vuex的基本原理与使用方法,包括store的创建与使用、getter的定义、action与mutation的区别,以及如何解决页面刷新时Vuex数据丢失的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue

vue 简介及基本原理

vue官网简介:Vuex是Vue.js应用程序的状态管理模式+库。它充当应用程序中所有组件的集中存储,其规则确保状态只能以可预测的方式进行变更。它还与Vue的官方devtools扩展集成,以提供零配置时间旅行调试和状态快照导出/导入等高级功能。

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。

Vuex 和单纯的全局对象有以下两点不同:

  • Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
  • 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

		const store = new Vuex.Store({
		  state: {
		    count: 0
		  },
		  mutations: {
		    increment (state) {
		      state.count++
		    }
		  }
		})

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


		store.commit('increment')
		
		console.log(store.state.count) // -> 1

Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):


		new Vue({
		    el: '#app',
		    router,
		    store,
		    components: { App },
		    template: '<App/>',
		
		    created() { //刷新重新赋值,vuex
		        try {
		            let val = this.$store.state.saveVuexInfo.flag;
		            let list = JSON.parse(localStorage.getItem("saveVuexInfo"))
		            if (!val && list.flag) {
		                this.$store.dispatch("setVuexInfo", list)
		            }
		        } catch (e) {}
		    }
		})

有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:


		computed: {
		  doneTodosCount () {
		    return this.$store.state.todos.filter(todo => todo.done).length
		  }
		}

如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它——无论哪种方式都不是很理想。

Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
vue 项目使用
安装vuex
npm install vuex --save
创建store文件
		
		引入vuex 
		
		import Vue from "vue";
		import Vuex from "vuex";
		Vue.use(Vuex);
		
		// 简单的应用
		// state (全局变量的数据)
		// getters (用来获取数据的方法)
		// actions (跟后台接口打交道的方法)
		// mutations (存储数据的方法)
		
		// vueComponent(组件) -> actions 
		// -> mutations -> state -> vueComponent(组件)
		
		// vueComponent(组件) -> getters -> state

创建一个store

new一个store文件,根据需求:
例如:


		let store = new Vuex.Store({
		    state: {
		        saveVuexInfo: {
		            saveAccountingId: '', //保存进入账套管理页面的账套id
		            accountingStandard: '', // 进入账套新窗口的会计准则
		            accountingName: '', // 进入账套新窗口的公司名称
		            flag: '', //用来保存vuex中是否存储值。
		        }
		    },
		    getters: {
		        getSaveVuexInfo(state) {
		            return state.saveVuexInfo
		        }
		    },
		    actions: {
		        setAccountingId({ commit, state }, id) { //保存进入账套管理页面的账套id
		            commit("setAccountingId", id);
		        },
		        accountingStandard({ commit, state }, accountingStandard) { // 进入账套新窗口的会计准则
		            commit("accountingStandard", accountingStandard);
		        },
		        accountingName({ commit, state }, accountingName) { // 进入账套新窗口的公司名称
		            commit("accountingName", accountingName);
		        },
		        setVuexInfo({ commit, state }, list) { // 用于main.js 刷新丢失
		            commit("setVuexInfo", list);
		        },
		    },
		    mutations: {
		        setAccountingId(state, id) {
		            state.saveVuexInfo.saveAccountingId = id;
		            state.saveVuexInfo.flag = 1;
		            localStorage.setItem("saveVuexInfo", JSON.stringify(state.saveVuexInfo));
		        },
		        accountingStandard(state, accountingStandard) {
		            state.saveVuexInfo.accountingStandard = accountingStandard;
		            localStorage.setItem("saveVuexInfo", JSON.stringify(state.saveVuexInfo));
		        },
		        accountingName(state, accountingName) {
		            state.saveVuexInfo.accountingName = accountingName;
		            localStorage.setItem("saveVuexInfo", JSON.stringify(state.saveVuexInfo));
		        },
		        setVuexInfo(state, list) {
		            state.saveVuexInfo = list;
		            localStorage.setItem("saveVuexInfo", JSON.stringify(state.saveVuexInfo));
		        },
		    }
		})

输出

export default store;

在main.js中引入并注入vue实例

		import store from "./store/store.js" // 引入vuex
		
		new Vue({
		    el: '#app',
		    router,
		    store,  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
		    components: { App },
		    template: '<App/>',
		
		    created() { //刷新重新赋值,vuex,
		        try {
		            let val = this.$store.state.saveVuexInfo.flag;
		            let list = JSON.parse(localStorage.getItem("saveVuexInfo"))
		            if (!val && list.flag) {
		                this.$store.dispatch("setVuexInfo", list)
		            }
		        } catch (e) {}
		    }
		})

使用

查:let val = this.$store.state.saveVuexInfo.flag;

改:(action异步):this.$store.dispatch(“setVuexInfo”, list)
(mutations同步):store.commit(‘loginSuccess’, null);

vuex刷新丢失

在使用vuex中,我们会把很多需要的值存在vuex中,作为全局的共享数据。但是在页面刷新的时候vuex里的数据会重新初始化,导致数据丢失。因为vuex里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,vuex里面的数据就会被重新赋值。

为了解决这个问题,我们可以借助浏览器的本地存储来解决,用本地储存和vuex的配合使用,高效完美的解决了这个 问题;

我们在每次初始化的时候,都判断vuex中是否存储有指定判断值,并且判断本地储存localStorage中是否有指定判断值;如果vuex中没有且本地中有,那么可以判断是vuex中的值丢失了。那么我们就可以异步调用,,将我们存储的localStorage中的值赋值给vuex中,即可;


		new Vue({
		    el: '#app',
		    router,
		    store,
		    components: { App },
		    template: '<App/>',
		
		    created() { //刷新重新赋值,vuex
		        try {
		            let val = this.$store.state.saveVuexInfo.flag;
		            let list = JSON.parse(localStorage.getItem("saveVuexInfo"))
		            if (!val && list.flag) {
		                this.$store.dispatch("setVuexInfo", list)
		            }
		        } catch (e) {}
		    }
		})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值