iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 20
0
Modern Web

NestJs 讀書筆記系列 第 20

VueJs - VueApollo Store

VueApollo Store

我想對 Vue 熟悉的讀者,在做前端緩存時大多數都是使用 Vuex ,不過當我們使用 Vue Apollo 時,它有自己的暫存區,如果這時我們又將資料暫存在 Vuex 中,這樣會導致我們有兩邊的暫存資料,所以這篇章我們來說明,如何更新在 Vue Apollo Store 的資料

我們使用 Mutation Create Author 以及 Query Authors 來做範例說明
Mutation篇章 中,我們所做的只是將 Mutation 的回傳結果 Push 到 Query Authors 的結果中,而不是更新 Store 的暫存區

下面的範例就是將 Mutation 結果暫存到 Store 中
我們能在 update 中取得 store 物件以及 Mutation 回傳結果
接著使用 store 提供的方法 readQuery 和 writeQuery
運作模式很簡單,將 store 中的 Authors 先取出來,再將 Create Author 的結果 Push 到 Authors ,最後再把 Authors 寫回 Store 中

createAuthor() {
    this.$apollo.mutate({
        mutation: CREATE_AUTHOR,
        variables: { ...this.newAuthor },
        update: (store, { data: { createAuthor } }) => {
            console.log(createAuthor);

            const { authors } = store.readQuery({ query: AUTHORS });
            console.log(authors)

            authors.push(createAuthor);
            store.writeQuery({ query: AUTHORS, data: { authors }});
        }
    })
}

當我們呼叫 Query Authors 就會更新資料,不用在重新發送一次 Query 的 API ,也不用將資料暫存在 Vuex 中,利用 Vue Apollo 提供的 Store 就能做到暫存的功能

以上就是 Vue Apollo 的全部介紹
接下來會做一個小練習,從 API 設計到前端頁面資料顯示,讓讀者可以更靈活運用 NestJs 以及 VueApollo


上一篇
VueJs - Vue Apollo Component
下一篇
實戰 - ToDo List
系列文
NestJs 讀書筆記31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言