iT邦幫忙

1

vue 畫面渲染時無法順利取到值,但確實是有值的

router

orderDetail/123

actions

get(context, data) {
            return new Promise((resolve, reject) => {
                getDetail(data).then(res => {
                    context.commit('SET_DETAIL', res.data);
                    resolve(res);
                }).catch(err => {
                    reject(err);
                });
            });
        },

確定有取到「res.data」,也有順利 SET_DETAIL

SET_DETAIL: (state, data) => {
            state.orderDetail = data;
        },
const order = {
    namespaced: true,
    state: {
        orderDetail: '',
    }
}

mutations

SET_DETAIL: (state, data) => {
            state.orderDetail = data;
        },

但卻有個詭異問題

created() {
    this.$store.dispatch('a/get', this.id)
    console.log(this.id) // 有取到 123
    console.log(this.row) // 沒有取到!?!?
  },
  computed: {
    id() {
      return this.$route.params.id
    },
    row() {
      return this.$store.state.order.orderDetail // 格式沒問題
    },
  }

但為什麼無法取到 this.row ⋯⋯
甚至有時候會取得到?!但就感覺慢半拍!

ShawnL iT邦新手 1 級 ‧ 2020-06-30 11:18:03 檢舉
雖然跟問題的"根本"無關,但提醒一下 console.log 預覽與點開後的狀態會不一樣,建議使用 JSON.parse(JSON.stringify(consoel.log('something'))) 來做深拷貝才能確保印出來的是該行程式碼「當下」的結果。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
dragonH
iT邦超人 5 級 ‧ 2020-06-29 23:40:36
最佳解答

我不知道你說的慢是有多慢

因為那很主觀

不過 action 都用 promise

dispatch 時用個 then 應該蠻合理的

codepen

看更多先前的回應...收起先前的回應...
froce iT邦大師 1 級 ‧ 2020-06-30 11:40:40 檢舉

我不知道你說的慢是有多慢

大概跟我感覺薪水總是不夠用一樣。XD

dragonH iT邦超人 5 級 ‧ 2020-06-30 11:47:12 檢舉

/images/emoticon/emoticon37.gif

火爆浪子 iT邦研究生 1 級 ‧ 2020-07-01 09:11:54 檢舉

就先是會得到 undefined 但其實再過一下就會有資料

火爆浪子 iT邦研究生 1 級 ‧ 2020-07-01 09:14:54 檢舉

我不知道是不是API回來的時間有點久,導致前端就先渲染了,然後會說某個欄位找不到值,例如「Error in render: "TypeError: Cannot read property 'coverPic' of undefined"」
但其實看畫面是有 coverPic 的

dragonH iT邦超人 5 級 ‧ 2020-07-01 09:36:59 檢舉

松松

大哥

你給的 code 沒看到你有 call api

也沒看到有啥 coverPic

火爆浪子 iT邦研究生 1 級 ‧ 2020-07-01 10:01:21 檢舉

getDetail 就是~

火爆浪子 iT邦研究生 1 級 ‧ 2020-07-01 10:54:44 檢舉

我是直接 {{ this.row.coverPic }} 顯示,但他仍然會出現 undefined 錯誤,但其實看畫面上是有值的,加上API返回的資料也確定有

火爆浪子 iT邦研究生 1 級 ‧ 2020-07-01 11:33:38 檢舉

我的問題好像是這個呢⋯⋯
https://www.cnblogs.com/muou2125/p/10727770.html
但還是報錯誤⋯⋯
我是在開頭的 div 加上 v-if="row"

火爆浪子 iT邦研究生 1 級 ‧ 2020-07-01 11:38:02 檢舉

我直接打印出 row 在 template 值都有直接出來⋯⋯
不曉得為什麼還是會 undefined
我確定的是 coverPic 是有值的,層級也對。

dragonH iT邦超人 5 級 ‧ 2020-07-01 13:33:24 檢舉

所以試過我說的

在 dispatch 加上 then 了嗎

火爆浪子 iT邦研究生 1 級 ‧ 2020-07-01 16:12:44 檢舉

我加了個 render data
成功後 then this.render = true
然後把最外層的 div 改成 v-if="render"
他還是說該值 undefined
但該值確定百分之百是有的

我要發表回答

立即登入回答