在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/C  HTML/ vue如何監(jiān)聽cookie的改變

vue如何監(jiān)聽cookie的改變

computed: {
      ...mapState({
        token: state => state.login.token,
        username: state => state.login.username,
        avatarUrl: state => state.login.avatarUrl,
        birthday: state => state.login.birthday,
        gender: state => state.login.gender,
        id: state => state.login.id,
        mobile: state => state.login.mobile,
      })
    },
    
    
store/login.js

const state = {
  username:getCookie("username"),
  avatarUrl:getCookie("avatarUrl"),
  birthday:getCookie("birthday"),
  gender:getCookie("gender"),
  id:getCookie("id"),
  mobile:getCookie("mobile"),
  token:getCookie("token"),
};
const mutations = {
  LOGIN(state,res){
    window.localStorage.clear();
    setCookie("token",res.data.token);
    setCookie("username",res.data.user.username);
    setCookie("avatarUrl",res.data.user.avatarUrl);
    setCookie("birthday",res.data.user.birthday);
    setCookie("gender",res.data.user.gender);
    setCookie("id",res.data.user.id);
    setCookie("mobile",res.data.user.mobile);
  },
}

如上,登錄的時(shí)候我把返回的值存為cookie,可是我登錄之后跳轉(zhuǎn)的個(gè)人中心頁面依然顯示的是未登錄的樣子,只有刷新一下才可以顯示登錄之后的,該怎么監(jiān)聽?

回答
編輯回答
敢試

不能監(jiān)聽cookie,應(yīng)該做頁面通信,在登錄成功后更新個(gè)人中心頁面

2017年5月15日 01:02
編輯回答
傻丟丟

同意faima的答案,狀態(tài)可以來源于cookie或webstorage,之后通過vuex或其他狀態(tài)機(jī)制更新(以vue狀態(tài)稱以示區(qū)別),視圖是被vue狀態(tài)驅(qū)動(dòng)而非被cookie驅(qū)動(dòng),因此和vue的雙向綁定的概念不同,監(jiān)控cookie本身其實(shí)并沒有什么意義。如果一定要做,有兩種方案:1.最傻瓜的辦法,在有路由更新的場(chǎng)景,添加守衛(wèi),每次獲取cookie的值之后再進(jìn)行路由變更;在request和response上添加攔截器獲取并更新cookie,缺點(diǎn)是不利于維護(hù)且需要同步執(zhí)行否則可能導(dǎo)致狀態(tài)沒有及時(shí)更新;2.通過頁面通信,從外部獲取狀態(tài)并更新到vue狀態(tài),組件可以通過vuex實(shí)現(xiàn)組件之間的狀態(tài)傳遞。

2017年10月15日 07:15
編輯回答
凹凸曼

在 MVVM 的架構(gòu)中,Cookie 一般是作為“M”,也就是 Model 存在,用來存儲(chǔ)和持久化數(shù)據(jù)。如果你想在視圖上看到效果,需要把數(shù)據(jù)放在 VM 里,所以,下面你應(yīng)該在 setCookie 的同時(shí)也把值賦給 state。

2017年12月4日 04:17