码迷,mamicode.com
首页 > 其他好文 > 详细

同步存储读取vuex中store中的值

时间:2020-05-10 21:08:55      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:方式   compute   窗口   put   技术   ESS   eth   eve   button   

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事件");
    });

同步存储读取vuex中store中的值

标签:方式   compute   窗口   put   技术   ESS   eth   eve   button   

原文地址:https://www.cnblogs.com/IwishIcould/p/12864667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!