同步存儲讀取vuex中store中的值


main.js

import store from "./store";

Vue.prototype.$store = store;


store中的index.js中

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    username: "",
  },

  // 同步  第一個形參 代表state
  //name形參代表的是  你此時傳遞過來的參數
  mutations: {
    getTopClickMenuName: (state, name) => {
      state.username = name; //賦值
    },
  },
  actions: {},
  modules: {},
});

A頁面設置值

<van-button type="warning" @click="add">++</van-button>
<van-button type="danger">{{ $store.state.username }}</van-button>

methods: {
    //調用函數,
    add() {
      this.$store.commit("getTopClickMenuName", this.$store.state.username + 1);
    },
},

B頁面獲取值(第以種方式直接獲取)

<h1>{{ $store.state.username }}--</h1>

第二種方式使用computed

<h1>{{ atoB }}--</h1>

computed: {
    atoB() {
      return this.$store.state.username;
    },
  },

我們發現在刷新頁面的情況下。
store中的值,會丟失的。在刷新的時候,保留在本地
在app.vue中寫

 created() {
    //在頁面加載時讀取sessionStorage里的狀態信息
    if (sessionStorage.getItem("username")) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("username"))
        )
      );
    }

    //在頁面刷新時將vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem("username", JSON.stringify(this.$store.state));
    });
  },

總結一下beforeunload事件

當瀏覽器窗口關閉或者刷新時,會觸發beforeunload事件。

window.addEventListener("beforeunload", () => {
      console.log("當瀏覽器窗口關閉或者刷新時,會觸發beforeunload事件");
    });


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM