Vuex value transfer problem

practice using simple vuex to pass values
store.js:

const store = new Vuex.Store({
  // 
  state: {
    headImg: ""
  },
  mutations:{
    newImg(state,msg){
      state.headImg=msg;
    }
  }
})

pass value: this.$store.commit ("newImg", val.HeadImgUrl);
receive:

<template>
  <div>
    <img :src="msg" alt="">
  </div>
</template>
<script>
  export default {
    name: "detail",
    data () {
      return {
        msg: ""
      }
    },
    created(){
      this.msg=this.imgSrc;
    },
    computed: {
      imgSrc () {
        return this.$store.state.headImg; //vuex
      }
    }
</script>

the problem is that this value is gone when the page is refreshed. How can it still exist after refreshing the page? (not long after learning vue, please give me some advice)

Mar.06,2021

this.$store.commit ("newImg", val.HeadImgUrl); this method writes to

created(){
  this.$store.commit("newImg",val.HeadImgUrl);
  this.msg=this.imgSrc;
},

The status in

store is reinitialized after refreshing, and can be solved through local storage

const store = new Vuex.Store({
  // 
  state: {
    headImg: JSON.parse(sessionStorage.getItem('headImg')) || ""
  },
  mutations:{
    newImg(state,msg){
      sessionStorage.setItem('headImg', JSON.stringify(msg))
      state.headImg=msg;
    }
  }
})

essentially $store mounts an object in the vue instance, when the page is refreshed, the vue instance is regenerated, and the value in $store no longer exists.


save a copy of the value in localhost. The default value of state in vuex is the value in localstorage.

Menu