亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vuex通過getters訪問數(shù)據(jù)為undefined問題及解決

 更新時間:2022年08月31日 15:43:46   作者:qiqingfu  
這篇文章主要介紹了vuex通過getters訪問數(shù)據(jù)為undefined問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

getters訪問數(shù)據(jù)為undefined問題

本篇文章可能對你的幫助不大, 只是個人開發(fā)中的一些記錄。不同的業(yè)務(wù)和應(yīng)用場景可能問題不同。

在通過 uni-app 開發(fā)商城時,用戶快捷登錄之后,服務(wù)器返回一個 token 數(shù)據(jù),我將其同步到 vuex module下的 user 模塊中。

然后從登錄頁返回到用戶頁,并發(fā)起 http 請求,獲取用戶的個人信息。

但是在請求時,我會在請求攔截器中獲取 vuex 中的 token 數(shù)據(jù)。如果存在就攜帶到請求頭中和服務(wù)器做 OAuth 驗證。如果不存在就直接不攜帶 token。

用戶登錄成功之后,返回到用戶頁發(fā)起請求,但是獲取用戶信息接口是必須做 OAuth 驗證的。問題在于在請求攔截器中 不能通過 vuex 的 getter 正確獲取到 token值,而是返回 undefined。

request.js

import Http from "../xxx/http";
import store from "../sotre";
const request = new Http({
? baseURL: xxxxx,
? timeout: 50000,
? // 省略
});
request.interceptors.request.use((config) => {
? let token, g_t;
? if (
? ? (g_t = store.getters[`user/token`]) ||
? ? (g_t = Storage.get(USER_TOKEN_KEY))
? ) {
? ? token = g_t.token || null;
? }
? if (token) {
? ? config.header["Authorization"] = "Bearer " + token;
? }
? return config;
});

問題在于 g_t = store.getters[user/token] 獲取的值為 undefined。

經(jīng)過排查發(fā)現(xiàn),vuex 中 getters 下的通過 state 獲取的字段實現(xiàn)沒有在 state 中定義。而是通過異步登錄之后,才將其設(shè)置到 user 模塊下的 state 中,使其變?yōu)椴皇琼憫?yīng)式的。

寫一個類似例子

<!DOCTYPE html>
<html lang="en">
<head>
? <meta charset="UTF-8">
? <title>Title</title>
</head>
<body>
<div id="app">
? <p>姓名: {{ realName }}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.3.0/dist/vuex.js"></script>
<script type="module">
? Vue.use(Vuex);
? const store = new Vuex.Store({
? ? state: {},
? ? mutations: {
? ? ? change(state, data) {
? ? ? ? state.name = data;
? ? ? }
? ? },
? ? getters: {
? ? ? name: state => {
? ? ? ? return state.name;
? ? ? }
? ? }
? });
? new Vue({
? ? el: "#app",
? ? store,
? ? data: {
? ? ? message: "Hello"
? ? },
? ? computed: {
? ? ? realName() {
? ? ? ? return this.$store.getters.name;
? ? ? }
? ? },
? ? created() {
? ? ? setTimeout(() => {
? ? ? ? this.$store.commit('change', 'zhangsan');
? ? ? })
? ? }
? })
</script>
</body>
</html>

異步代碼執(zhí)行的時候, state 中并沒有 name 屬性。所以一開始 getters 下的 realName 就算是 undefined。異步代碼提交的 commit,在想 state 中新增 name 字段,但是它已不是響應(yīng)式的。

解決方法:

就是提前在 state 中定義 getters 需要的某些字段,異步變更 state 中的字段它也是響應(yīng)式的。getters 的值也會進(jìn)行計算。

getters 類似于 vue 中的計算屬性。

修改上面的代碼為:

const store = new Vuex.Store({
? ? state: {
?? ??? ?name: ""
?? ?},
? ? // 省略...
? }) ?

這樣 getters 的值會根據(jù) name的值改變而進(jìn)行計算。

項目中的代碼比上面的例子更復(fù)雜,但是問題是類似的。經(jīng)過排查后才發(fā)現(xiàn),所以在博客中總結(jié)一下。

小結(jié):使用 vuex 時, getters 中需要計算的 state 屬性一定要提前聲明,使其成為響應(yīng)式的值。

vuex getters(組件mounted調(diào)用)使用注意

邏輯

  • state存儲數(shù)據(jù)(一開始為空數(shù)據(jù),通過網(wǎng)絡(luò)請求后更新數(shù)據(jù))
  • 在組件mounted中先調(diào)用actions方法通過mutations更新state數(shù)據(jù),
  • 接著組件mounted在調(diào)用getters 操作state中的數(shù)據(jù),供組件使用
mounted(){
    // 進(jìn)入組件立即發(fā)送網(wǎng)絡(luò)請求獲取商品信息
    this.$store.dispatch('detail/getCommdityInfo',this.skuId)
    console.log(this.skuInfo) //為undefined
    console.log(this.cateNav) //控制臺報錯
}
state: {
    commdityData:{}
  },
  mutations: {
    SET_COMMDITY_LIST(state,value){
      state.commdityData = null
      // 將商品信息存入組件內(nèi)
      state.commdityData = value
      console.log('state.commdityData',state.commdityData)
    }
  },
  actions: {  
    async getCommdityInfo(context,query){
      const res = await getCommdityDetail(query)
      context.commit('SET_COMMDITY_LIST',res.data.data)
    }
  },
  getters:{
    skuInfo:state => state.commdityData.skuInfo,
    cateNav:state => {
        const {category1Name,category2Name,category3Name} = state.commdityData.categoryView 
        return [category1Name,category2Name,category3Name]
    },
    
  }

結(jié)果報錯:組件在mouted 調(diào)用getters屬性時,getters屬性讀取state數(shù)據(jù)(一開始為空),讀取不到數(shù)據(jù)

**原因:**組件調(diào)用actions執(zhí)行異步網(wǎng)絡(luò)請求,通過mutations更新state數(shù)據(jù)還沒有來得及執(zhí)行

解決方案

更改getters中操作數(shù)據(jù)的屬性,try-catch錯誤處理

cateNav:state => {
      // 使用情景,組件在mounted中調(diào)用,getters 的屬性時,此時state未更新;解構(gòu)會出錯,所以要錯誤處理?。?
      try{
        const {category1Name,category2Name,category3Name} = state.commdityData.categoryView 
        return [category1Name,category2Name,category3Name]
      }
      catch{
        return {}
      }
    },

?。。∽⒁猓涸诮M件的methods中寫方法調(diào)用則可正常使用getters的數(shù)據(jù)?。?/strong> 

控制臺輸出:

1:mounted 輸出

2:methods 方法的輸出

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論