vue中vuex+axios+sessionStorage 本地持久化

前端之家收集整理的这篇文章主要介绍了vue中vuex+axios+sessionStorage 本地持久化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

项目中有一个中国省市的列表,每次使用都请求接口,就想把这个数据放到vuex中,每次使用get一下就好了。基于这样的目的来完成。记录一下

目录
/store

  • index.js
  • province.js
  • getters.js

index.js

import vue from 'vue'
import vuex from 'vuex'
import province from './province'
import getters from './getters'
vue.use(vuex)
const store = new vuex.Store({
    modules: {
        province
    },getters
})
export default store

province.js

import http from '../api/http'

const province = {
state: {
provinceList: []
},mutations: {
SET_PROVINCE (state,province) {
sessionStorage.setItem('province',JSON.stringify(province))
state.provinceList = province
}
},actions: {
getProvince ({commit,store}) {
http({
methods: 'get',url: '/common/get-province'
}).then((res) => {
//console.log(res)
if (res.data.errcode === 200) {
commit('SET_PROVINCE',res.data.data)
}
})
}
}
}

export default province

getters.js

const getters = {
  provinceList: state => {
    if (state.province.provinceList.length === 0) {
      state.province.provinceList = JSON.parse(sessionStorage.getItem('province'))
    }
    return state.province.provinceList
  }
}

export default getters

login.vue
登录的时候调用一下 actions 中的访问数据的接口

this.$store.dispatch('getProvince')

hellow.vue
页面中 使用computed 来把数据更新到页面

computed: {
    cityList () {
        return this.$store.getters.provinceList
    }
}

数据如何流转起来的
// 存储数据
1、首页登录的时候 this.$store.dispatch('getProvince') 一下;
2、调用了vuex中 actions 中的 getProvince;
3、actions 中的 getProvince 通过 axios 来访问接口获得数据;
4、访问接口成功, commit('SET_PROVINCE',res.data.data) 调用了 mutations 中的 SET_PROVINCE;
5、将上一步的数据 存入 seesionStroage 中,并更新到state中

// 读取
1、hello.vue 页面 在computed中 使用 return this.$store.getters.provinceList;
2、访问到了 getters.js 中的 provinceList, 先判断state中的数据是否为空,为空就从sessionStorage中读取并存到 state中 ,hello.vue页面就读取了数据

SF 的markdown 真难用

猜你在找的程序笔记相关文章