gogogo
管理员
管理员
  • UID25
  • 粉丝0
  • 关注0
  • 发帖数1377
阅读:4767回复:1

vuex store 缓存存储原理

楼主#
更多 发布于:2020-10-21 09:21
  • vuex 的设计是将数据存在一个对象树的变量中,我们的应用(vue应用)从这个变量中取数据,然后供应用使用,当将当前页面关闭, vuex 中的变量会随着消失,重新打开页面的时候,需要重新生成。
  • 而,浏览器缓存(cookie,localstorage等)是将数据存到浏览器的某个地方,关闭页面,不会自动清空这些数据,当再次打开这个页面时,还是能取到之前存在浏览器上的数据(cookie,localstorage等)。
  • 要使用 vuex 还是使用浏览器缓存,要看具体的业务场景。比如:像用户校验的 token 就可以存在 cookie 中,因为用户再次登录的时候能用到。而像用户的权限数据,这些是有一定安全性考虑,且不同用户的权限不同,放在 vuex 中更合理,用户退出时,自动销毁。
  • 其次,vuex 中的 state 是单向的,也可以异步操作,这两个没有冲突。
  • vuex 中的 state 的设计思路是保证数据的一致性和连续性,而让 state 中的值只能通过 action 来发起 commit,进而改变 state 中的值。
  • 而,action 中是 同步 还是 异步,都是单向地改变 state 中的值。
gogogo
管理员
管理员
  • UID25
  • 粉丝0
  • 关注0
  • 发帖数1377
沙发#
发布于:2020-10-21 09:23


关于vue store 全局缓存的问题




个人使用 vuex 的管理方式
state :对数据的全局存储
getter: 可以理解为computed ,对数据进行计算
mutations :对数据的同步更改
actions:对数据的异步更改(实现异步操作)
module: 将 store 分割成模块



state,getter,mutations,actions的使用 和 访问 (使用this.$store 需要在main函数引用store)




import Vue from 'vue';
import Vuex from 'vuex';
const store = new Vuex.Store({
state: {
a: 1,
list: [],
age: [],
},
// 计算数据 (操作数据)暂时还没有实际用到, mutations可以实现数据的同步更新,因此暂时没用到
getters: {
add() {
return state.a += 1
}
},
// 同步异步请求的数据到state中,也可写单独的函数进行调用 同步数据更新
mutations: {
// 同步异步请求的数据
getList(state, res) {
state.list = res;
},
// 单独的函数进行调用 同步数据更新 (文章下面有调用方式)
getCurrName(state, res) {
       const newState = state;
       state.list.forEach((item) => {
       if (item.name === res.name) {
       newState.age = item.age;
       }
       })
     },
},

// 数据异步请求, 一般用于拿取api接口数据(全局数据)
actions: {
 getList({ commit }, params) {
return new Promise((resolve) => {
const response = [{"name":"zhang", "age":12},{"name":"yu","age":25},{"name":"feng","age": 24}]
resolve(response);
})
}
},
})
export default store;










// 调用mutations 方法同步数据更新
this.$store.commit({
    type: 'getCurrName',
    name: 'zhang',
 });
 // 调用actions 方法实现数据的实时请求
 store.dispatch({
   type: 'getList',
}).then(() => {});
// 获取state的数据
this.$store.state
// 访问getters中的add
store.getters.add






module的使用



const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}
export default store;

//  访问
this.$store.state.moduleA
this.$store.state.moduleB




https://blog.csdn.net/weixin_44959893/article/details/100655602?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param
游客


返回顶部