解决存储vuex数据,页面刷新后vuex数据被清空了的问题

49 阅读1分钟

1.vuex刷新后数据会被清除 在这里插入图片描述

在这里插入图片描述 在这里插入图片描述 2.可以监听用户是否手动刷新页面,刷新之前先把vuex的数据存储在localStorage里面,页面加载时读取localStorage里的状态信息给vuex赋值;赋值后再清空localStorage

打开app.vue文件,写入以下代码

<script setup>
import { useStore } from 'vuex'
import { onMounted,ref,reactive} from 'vue';
//vuex使用
const store = useStore()
onMounted(()=>{
   //在页面刷新时将vuex里的信息保存到localStorage里
    window.addEventListener("beforeunload",()=>{ 
      localStorage.setItem("userComMsg",JSON.stringify(store.state))
    });
    //在页面加载时读取localStorage里的状态信息
    if(localStorage.getItem("userComMsg")){ 
      Object.assign(store.state,JSON.parse(localStorage.getItem("userComMsg")));
      //使用后清除内存
      setTimeout(function () { 
        localStorage.removeItem("userComMsg");
      },300)
    }
})
</script>