1. 程式人生 > >vuex 資料狀態管理,重新整理資料不丟失 這篇就夠了

vuex 資料狀態管理,重新整理資料不丟失 這篇就夠了

vue 腳手架安裝,這裡我就不介紹了 說重點 !

安裝 vuex

npm install vuex --save

安裝成功後 ,現在我們就可以使用 vuex 了

1: 先在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 重新整理資料 丟失的問題了 !