同步存储读取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事件");
    });

相关文章

这篇文章我们将通过debug源码的方式来带你搞清楚defineAsync...
欧阳老老实实的更新自己的高质量vue源码文章,还被某2.6k st...
前言 在Vue3.5版本中响应式 Props 解构终于正式转正了,这个...
组合式 (Composition) API 的一大特点是“非常灵活”,但也因...
相信你最近应该看到了不少介绍Vue Vine的文章,这篇文章我们...
前言 在欧阳的上一篇 这应该是全网最详细的Vue3.5版本解读文...