Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

[Vue]Vue3重新渲染元件的方式-Vue3 rerender a component

內容目錄

Vue3重新渲染元件的方式-Vue3 rerender a component

研究了一下vue3中如果要重新讀取元件(component)的作法,有時候真的無法靠資料更新之類的達到目的時,就必須重新讀取/渲染元件。一開始要實作這件事時還真的沒什麼頭緒,直覺想到用v-if來實作,大概長這樣。

v-if法

簡單來說就是用renderComponent變數來控制component的起動

<template>
    <my-component v-if="renderComponent" />
</template>

在setup中設定,nextTick是當畫面渲染完後再執行

import { nextTick, ref } from 'vue';
const renderComponent = ref(true);

const forceRerender = async () => {
  // 移除component的DOM
  renderComponent.value = false;

    // 等待主畫面
    await nextTick();

    // 重新加入這個component
  renderComponent.value = true;
};

再找個地方執行forceRerender就可以,基本原理就是將component移除、重新創建、掛載。
但查了一下資料後,發現有更漂亮的作法。

鍵值改變驅動Key-Changing

我們只要新增一個屬性在component上,透過屬性值的改變就能觸發vue更新component。

<template>
    <my-component :key="componentKey" />
</template>

透過forceRerender來更改componentKey的值

import { ref } from 'vue';
const componentKey = ref(0);

const forceRerender = () => {
  componentKey.value += 1;
};

接下來只要觸發forceRerender,就能更新component。
但老實說我其實還不太確定為什麼這個做法較為優秀,歡迎留言討論XD

很推薦參考這篇參考資料

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *