前端常用全局通信方法(vuex localStorage sessionStorage)

1.localStorage 特点 能永久存储 不手动删除 或者清理浏览器缓存 就一直在

A页面存储
localStorage.setItem('enterpriseInfo', JSON.stringify(arr))

B页面拿值
const data = JSON.parse(localStorage.getItem('enterpriseInfo'))

2.sessionStorage 特点 只在当前页面有效 关闭浏览器页面时会被清除

A页面存储
sessionStorage.setItem('enterpriseInfo', JSON.stringify(arr))

B页面拿值
const data = JSON.parse(sessionStorage.getItem('enterpriseInfo'))

3.vuex vue全局通信工具

先简单介绍下vuex里面的方法

state: {} 定义数据

mutations: {} 我理解为定义方法的(修改state里面的值)

actions: {} 指派mutations  在里面可以用 commit调用mutations里面的方法

modules: {}  // 用于模块化

下面举个例子

假设这个文件是store里面的archive.js  一般每个业务去定义一个存储文件 不要都写在index.js里面
store/index.js里面   import archive from './archive'

state: {
  retrievalItem: {},
},
mutations: {
  SET_RETRIEVAL_ITEM: (state, data) => { // 这里的state参数就是上面的state
    state.retrievalItem = data
  },
},
用法1
页面调用时 this.$store.commit('archive/SET_RETRIEVAL_ITEM', arr)
取值直接   this.$store.state.archive.retrievalItem
注意:如果直接是store里面index.js 则不需要加一层archive
直接       this.$store.commit('SET_RETRIEVAL_ITEM', arr)
用法2  页面methods里
methods: {
  ...mapMutations("archive", [
    "SET_RETRIEVAL_ITEM",
  ]),
}
this.SET_RETRIEVAL_ITEM(arr);

actions: {
  updateItem({ commit }, data) {
    commit('SET_RETRIEVAL_ITEM', data)
  },
}
用法1
页面调用时 this.$store.dispatch('archive/updateItem', arr);
用法2
methods: {
  ...mapActions("archive", [
    "updateItem",
  ]),
}
this.updateItem(arr);

modules一般在store里面的index.js才有  作用就是模块化的 便于管理不用模块的vuex文件
import archive from './archive'
modules: {
  archive
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值