iT邦幫忙

0

vue+vuex+vue-router 做SPA問題,子分頁無法獲取父分頁的資料

  • 分享至 

  • xImage

我的vue-router設定
https://ithelp.ithome.com.tw/upload/images/20220527/20122444HYYwYtqcob.png

在tour.vue中抓取資料放到vuex內,想將它作為所有子頁面的全域變數,試過在await後log是可以讀取到資料的
https://ithelp.ithome.com.tw/upload/images/20220527/20122444lNfBSTOUbC.png

現在問題是在子頁面內無法抓到上述提到的資料,會顯示undefined
https://ithelp.ithome.com.tw/upload/images/20220527/201224440cX962lp5R.png

想請教各位有SPA經驗的解法

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2022-05-27 10:56:52 檢舉
1. 用 vue devtools 看 state,確認一下state是不是你要的。
2. 你這該給的是你的store,不是vue router,vuex 是全域狀況,非子原件也能取得,跟你router沒有關係。
adha9990 iT邦新手 5 級 ‧ 2022-05-27 11:22:05 檢舉
我目前發現是因為fetch後會延遲取得資料
在我給它setTimeout延遲一秒後可以取得資料
但我子頁面需要等待資料出來
是否有辦法先等待父頁面fetch完資料再載入子頁面?
adha9990 iT邦新手 5 級 ‧ 2022-05-27 11:51:17 檢舉
我解決了這問題了感謝各位!
我在vue-router內新增beforeEnter後就能在子頁面讀取到資料了
froce iT邦大師 1 級 ‧ 2022-05-27 13:04:50 檢舉
這種狀況我個人比較建議去監聽 state 變動。
至少你可以做 loading animation 而不是整頁卡住。
https://segmentfault.com/a/1190000023424136
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
greenriver
iT邦研究生 5 級 ‧ 2022-05-27 15:57:37

如果有用到fetch或axios,
我大致是這樣用。
在children,使用watch監控。
因為渲染流程是 : Parent.vue->Children.vue->Parent.vue的fetch/axios返回的資料
當獲得fetch返回值時,Children.vue早已渲染完,所以會出錯。

//Parent.vue
<script setup>
    import Children from './....../Children.vue'
    import {ref} from 'vue'
    
    cosnt childrenData = ref()
    axios.get('http://.....com')
    .then((res)=>{
        childrenData.value = res.data
    })
</script>
<template>
    <Children :childrenData = childrenData />
</template>
//Children.vue
<script setup>
    import {ref} from 'vue'
    
    cosnt props = defineProps({
        childrenData : Object
    })
    
    const needData = ref(0) //通常我會給個初始值,就算沒收到fetch的返回值,至少也不會出錯    
    watch(()=>props.childrenData,(newVal)=>{
        needData.value = newVal
    })
</script>
<template>
    {{needData}}
</template>

我要發表回答

立即登入回答