zoukankan      html  css  js  c++  java
  • 同步存储读取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事件");
        });
    
  • 相关阅读:
    5.6
    5.6
    4.30数据结构
    4.30
    POJ3616
    4.29
    4.28
    186周赛
    CF1267G Game Relics
    CF763E Timofey and our friends animals
  • 原文地址:https://www.cnblogs.com/IwishIcould/p/12864667.html
Copyright © 2011-2022 走看看