vuex与vuex-persistedstate 插件固化数据
一,vuex与vuex-persistedstate 插件固化数据 的小案例
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><title>Vuex基础案例</title></head><body><div id="app"><h1>计数器应用</h1><p>当前计数值:{{ count }}</p><button @click="increment">增加</button><button @click="decrement">减少</button></div><script src="./三阶段作业/vue-3.js"></script><!-- 引入 Vuex 库 --><script src="./vuex@4.0.0_dist_vuex.global.js"></script><!-- 使用vuex-persistedstate固化数据 --><script src="./unpkg.com_vuex-persistedstate@4.1.0_dist_vuex-persistedstate.umd.js"></script><script>const { createApp } = Vue;const { createStore } = Vuex;const createPersistedState = window.createPersistedState; // 导入 vuex-persistedstate 插件const store = createStore({state() {return {count: 0,};},mutations: {increment(state) {state.count++; // 状态变更方法},decrement(state) {state.count--; // 状态变更方法},},plugins: [createPersistedState()], // 添加 vuex-persistedstate 插件});createApp({computed: {count() {return store.state.count; // 从 Vuex 的 store 中获取状态}},methods: {increment() {store.commit('increment'); // 提交 mutation 来修改状态},decrement() {store.commit('decrement'); // 提交 mutation 来修改状态}}}).use(store).mount("#app"); // 在 Vue 应用中使用 Vuex 的 store 实例</script></script></body>
</html>
二,数据持久化:
刷新页面,vuex里面数据丢失、清空。有时候我们需要把一些数据固话到本地,即使刷新也不能清空,例如:登陆状态、token等。这是就需要用到vuex数据持久化
//需要先下载插件
npm install vuex-persistedstate --save 或者 使用
yarn add vuex-persistedstate --save
//在vuex初始化时导入插件
import persist from 'vuex-persistedstate'
//并使用
export default new Vuex.Store({state: {},mutations: {},actions: {},modules: {},plugins: [new persist({storage: window.localStorage,}),],//会自动保存状态,刷新时不会丢失
})
© 著作权归作者所有,转载或内容合作请联系作者

喜欢的朋友记得点赞、收藏、关注哦!!!