一、使用vuex进行数据缓存

官网介绍:Vuex是一个专门为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

我们理解:Vuex是采用集中式管理组件依赖的共享数据的一个工具vue插件,可以解决不同组件数据共享问题

节点说明:

state管理数据,管理的数据是响应式的,当数据改变时驱动视图更新。=>类似与组件的data

mutations更新数据,state中的数据只能使用mutations去改变数据

actions 把数据提交给mutations,可以进行异步操作,不能直接修改state

getters 对数据获取之前进行再次编译,可以理解为state的计算属性

modules 它可以来帮我们的状态树分隔成不同的模块,由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

2.安装vuex

npm install vuex --save

3.在src下新增store文件夹

4.在store下新增modules文件夹

5.在modules下新增form.js、user.js文件

// form.js
const state = {
	count: 0 // 数量
};

const mutations = {
	SET_COUNT: (state) => {
		state.count++;
	}
};

const actions = {
	SET_COUNT_ASYNC(context) {
		setTimeout(() => {
		context.commit("SET_COUNT")
		}, 1000)
	}
};

export default {
	state,
	mutations,
	actions
};

// user.js
const state = {
	name: 0, // 姓名
	age: 0, // 年龄
};

const mutations = {
	SET_NAME: (state, data) => {
		state.name = data;
	},
	SET_AGE:(state, data) => {
		state.age = data;
	}
};

const actions = {};

export default {
	state,
	mutations,
	actions
};


6.在store下新增getters.js、index.js文件

// getters.js
const getters = {
	count: state => state.form.count,
	name: state => state.user.name,
	age: state => state.user.age
}

export default getters

// index.js
import { createStore } from 'vuex'
import form from './modules/form'
import user from './modules/user'
import getters from './getters' 

const store = createStore({
	modules: {
		form,
		user
	},
	getters
})

export default store

7.在main.ts中引入store

import { createApp } from 'vue'
import 'element-plus/theme-chalk/index.css';

// 新增store
import store from './store';

import App from './App.vue'
import router from './router'

createApp(App).use(router).use(store).mount('#app')

8.在vue中使用

<template>
	<h1>vuex中的数据{{ state.form.count }}</h1>
	<button @click="add(10)">++</button>
	<button @click="add_async(10)">异步</button>
</template>
<script setup>

import { useStore } from "vuex"

const {state,commit,dispatch} = useStore()

const add = () => {
	commit('SET_COUNT')
	console.log("store:", state.form.count)
}
const add_async = () => {
	dispatch('SET_COUNT_ASYNC')
	console.log("store:", state.form.count)
}
</script>