iT邦幫忙

2021 iThome 鐵人賽

DAY 19
1
Modern Web

Vue.js 進階心法系列 第 19

載入頁面,什麼時候發 API 適合?

我們想要找一個適合的地方送出 $store.dispatch('fetchUser', 1); 今天就來聊聊放在哪最適合

一開始,官網教 axios 的地方

Using Axios to Consume APIs — Vue.js

官網教我們用 axios,並且為了將 axios 的資料儲存起來,在 mounted 裡發 API 確保 data 的存取是沒問題的。

  mounted () {
    axios
      .get('https://api.coindesk.com/v1/bpi/currentprice.json')
      .then(response => (this.info = response))
  }

所以,如是你對發送 API 的問題,查閱了官網,就會把 fetchUser 寫在 mounted 上面

官網教 lifecycle 的地方

The Vue Instance — Vue.js

當 Vue 執行到 created 的時候,data 會進入 reactivity 系統上。

export default {
  name: 'About',
  data() {
    return {
      user: {
        name: 'chris'
      }
    }
  },
  beforeCreate() {
    console.warn('[component About] beforeCreate', this.user)
  },
  created() {
    console.warn('[component About] created', this.user)
  },
  beforeMount() {
    console.warn('[component About] beforeMount', this.user)
  },
  mounted() {
    console.warn('[component About] mounted', this.user)
  }
};

因為 created 的時候,data 已經宣告完畢,並且可以存取了,所以,如是你了解 lifecycle 就會把 fetchUser 寫在 created 上面

如果你用了 vue-router,看了官網

Navigation Guards | Vue Router

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  console.log('[router beforeEach]');
  next()
})

會發現 beforeEach 比 component 還要早觸發,如果想要讓回傳的資料更早拿到讓頁面載入時,不要看見空白頁,再跳出資料的話,放在 befoeEach 是你的好選擇。

如果你不想要每一頁都 fetchUser

Per-Route Guard, Navigation Guards | Vue Router

通常都是特定頁面,才需要特定資料。
像 fetchUser,通常就是有使用者詳細資料的頁面才會需要。
所以,並不是每一頁都要打這一支 API,所以如果可以分成每一頁才需要的 API 這樣使用上就有效率多了,管理上也方便管理

這時,你就需要 beforeEnter

  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
    beforeEnter: (to, from, next) => {
      console.log('[router beforeEnter]');
      next()
    }
  },

透過 beforeEach 就可以在頁面載入之前,將請求送出去,並且會等待請求回來完成,才載入畫面。

如果在 beforeEach 寫下了 if (to.path === "/user") 這樣的判斷,就表示你需要 beforeEnter,透過 beforeEnter 也可以在頁面載入之前,將請求送出去,並且會等待請求回來完成,才載入畫面,而且各別畫面各別設定。


上一篇
用兩支 API 實作新增資料與上傳檔案
下一篇
其它的 lifecycle 或 vue router 的 hook
系列文
Vue.js 進階心法30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言