1. 程式人生 > >localstorage解決vuex重新整理資料消失問題

localstorage解決vuex重新整理資料消失問題

ps:此例項僅僅展示vuex的用法,並不適用於頁面跳轉傳參!!!

注:主要思路就是把傳遞的引數儲存到localstorage中 並寫入到state中

1、state.js

const state={
setguessid:{}
}

export default state

2、

/*儲存mutations相關的常量*/

export const SET_GUESSID='SET_GUESSID'

3、

import * as types from './mutation-types'

const mutation={
 /*兩個引數  state是獲取state.js的資料  第二個引數就是提交的引數*/
 [types.SET_GUESSID](state,setguessid){
  
  state.setguessid=setguessid
 }
}

export default mutation

4、

/*stations對映  從getters中取資料到元件中*/

export const setguessid=state=>state.setguessid

5、index_guesslike.vue

import {mapMutations} from 'vuex'

  methods:{
  selectItem(item){
        this.$router.push({
      path:`/mtindex/${item.id}`      //設定帶有引數的二級路由
         });
         this.setguessid(item.id);  //寫入store中
         localStorage.setItem("segid",item.id);  //把點選的id放到localstorage中
        
         
    },
...mapMutations({
    setguessid:'SET_GUESSID',
  })  
  }

6、guess_you_detail.vue

import {mapMutations,mapGetters} from 'vuex'

computed:{  
       ...mapGetters([
       'setguessid'
        ]),
        issetguessid:function(){
        var lc_z=localStorage.getItem("segid");
        if(this.setguessid!=lc_z){    //當前傳遞的id值與localstage做對比 如果不相等則賦值
        this.setloguessid(lc_z);          
        } 
        return this.$store.state.setguessid;
        }   

      },

mounted(){
//console.log(this.issetguessid);
    axios.get(''''''''''''.json').then((res)=>{        
    var data_shopbanner=res.data.shopbanner[this.issetguessid-1];       注意:this.issetguessid-1              
this.$nextTick(()=>{   //this.$nextTick()方法保證dom載入完成
           this.scroll= new BScroll(this.$refs.menuwrapper,{bounce: false,click:true}); 
       });                    
    })        
},
methods:{
    ...mapMutations({
    setloguessid:'SET_GUESSID'
  }) 
   
   
}