vuex 数据状态管理,刷新数据不丢失 这篇就够了

5,713 阅读2分钟

vue 脚手架安装,这里我就不介绍了 说重点 !

安装 vuex

npm install vuex --save

安装成功后 ,现在我们就可以使用 vuex

先在src 目录下建立 store 文件夹 , 文件目录如图

这里我先介绍下 每个文件的用处:
1 : index.js 这里是个入口文件

import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import state from './store'
import mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
    actions,
    getters,
    state,
    mutations
})

把我们需要的文件 都引入里面 ,注入并导出!

2 : store.js 文件 ,这是我们初始化数据的 ,也是之后我们存数据的地方,这里我先初始化一个 review 空的对象 !

const state = {
  review: {}
}

export default state;

3:mutation-types.js 这里是我们存常量的 ,方便我们之后在 mutations 里面调用 !
这里我先等一个常量为 : SET_REVIEW

export const SET_REVIEW = "SET_REVIEW"

4:getters.js 这个你可以看着是个 vue 的计算属性:

export const review = state => state.review

5:mutations.js , 提交 mutations 是更改 vuex中 store 中状态的 唯一方法

import * as types from './mutation-types'
const mutations = {
  [types.SET_REVIEW](state, review) {
    console.log("review", review)
    state.review = review
  },
}

export default mutations

6:action.js , Action 类似于 mutation,不同在于:Action 提交的是 mutation,而不是直接变更状态。 Action 可以包含任意异步操作。
简单的说 : 它是 操作 mutations 的 ,现实异步操作!
这里我是获取数据,暂时用不到 action.js

代码比较简单,我就直接贴了:
index.vue 首页:

<!--  -->
<template>
  <div>
      <span @click="linkTo()">链接跳转</span>
  </div>
</template>

<script type='text/ecmascript-6'>
import { mapMutations } from "vuex";
export default {
  data() {
    return {};
  },

  mounted() {
    this.getReviewData();
  },

  methods: {
    getReviewData() {
      let _this = this;
      _this.$http
        .get("api/review/needlist")
        .then(function(response) {
          console.log(response.data);
          if (response.data.code === 0) {
            let list = response.data.list;
            _this.setReview(list);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    linkTo(){
        this.$router.push({path:'review'});
    },

    ...mapMutations({
      setReview: "SET_REVIEW"
    })
  }
};
</script>
<style scoped>
</style>

这是vue 组件的 基本结构
在 methods 写个 获取数据的方法 getReviewData() !
在 mounted 生命周期里调用获取数据方法

关键:

我们使用 vue 提供的语法糖 ,来把数据存到 store 里:

引入 vuex 的 mapMutations 方法

import { mapMutations } from "vuex";

在 methods 里面写个 setReview ,它类似于 一个方法 , 和我们调用 其他方法完全一致 :

...mapMutations({
    setReview: "SET_REVIEW"
 })

最后我们把接口获取的数据 传入 这个方法中 , 就完成了 数据 存入 store 里了 !

_this.setReview(list);

接下来,我们就可以使用 store 里面的数据了

下面我们来获取 store 里面的数据 ,

新建一个 review.vue 组件
上代码 :

<!--  -->
<template>
  <div class="web">
    <ul>
      <li v-for="(item,index) in review" :key="index">
        <span>{{item.content}}</span>
      </li>
    </ul>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
export default {
  components: {
},

  data () {
    return {
    };
  },

computed:{
   ...mapGetters([
     'review'
  ])
},
mounted() {
    console.log(this.review);
},
 methods: {}
}

</script>
<style scoped>
</style>

获取数据 我们要引入 :

import {mapGetters} from 'vuex'

computed 生命周期里拿值
最后我们就可以渲染到页面了 !
最后上图 :

这里我们就可以在另一个页面 拿到数据了了 。

最后我们来说下 : vuex 刷新 数据丢失问题 ;
这里我们用到了 localStorage本地存储 。
我们可以在vue 组件里属于 , 在存数据的时候 同时也存到 localStorage 里面 。 在需要的地方 在从 localStorage 获取 !

这里我把 localStorage 放到 vuex 里面 , 不用在每个组件 都存一遍
我们再 mutations.js里面存数据

localStorage.setItem('review', JSON.stringify(state.review));

store.js 里面 加入以下代码 :

//防止页面刷新vuex中的数据丢失
for (var item in state) {
 localStorage.getItem(item) ? state[item] = JSON.parse(localStorage.getItem(item)) : false;
}

这里就解决了 我们vuex 刷新数据 丢失的问题了 !