vuex传值问题

练习使用简单的vuex来传值
store.js:

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

传值:this.$store.commit("newImg",val.HeadImgUrl);
接收:

<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>

问题是在刷新的时候这个值就没了,怎么让它在刷新完页面后还存在这个值呢?(刚学vue没多久,还请指点)


波斯汪
浏览 1242回答 2
2回答

慕沐林林

this.$store.commit("newImg",val.HeadImgUrl);这个方法写到created(){ &nbsp;&nbsp;this.$store.commit("newImg",val.HeadImgUrl);&nbsp;&nbsp; &nbsp;&nbsp;this.msg=this.imgSrc; },

萧十郎

store内的状态刷新后会重新初始化,可以通过本地存储解决const store = new Vuex.Store({&nbsp; // 定义状态&nbsp; state: {&nbsp; &nbsp; headImg: JSON.parse(sessionStorage.getItem('headImg')) || ""&nbsp; },&nbsp; mutations:{&nbsp; &nbsp; newImg(state,msg){&nbsp; &nbsp; &nbsp; sessionStorage.setItem('headImg', JSON.stringify(msg))&nbsp; &nbsp; &nbsp; state.headImg=msg;&nbsp; &nbsp; }&nbsp; }})
打开App,查看更多内容
随时随地看视频慕课网APP