Vue3 - daniel-qa/Vue GitHub Wiki

Vue3

資料傳遞

provide 與 inject

  • 父組件:provide

父組件透過 provide() 提供資料給子組件使用。

<script setup>
import { ref, provide } from "vue";

const message = ref("Hello Vue 3!");
provide("message", message); // 提供資料
</script>
  • 子組件:inject

子組件透過 inject() 來取用父組件提供的資料。

<script setup>
import { inject } from "vue";

const message = inject("message");

console.log(message.value); // "Hello Vue 3!"

生命週期鉤子 Lifecycle Hook

階段 鉤子名稱 描述
創建階段 onBeforeMount 組件掛載前執行。
onMounted 組件掛載後執行。
更新階段 onBeforeUpdate 組件更新前執行。
onUpdated 組件更新後執行。
銷毀階段 onBeforeUnmount 組件銷毀前執行。
onUnmounted 組件銷毀後執行。
錯誤處理階段 onErrorCaptured 捕獲子組件中的錯誤,當錯誤發生時觸發。

onMounted()

<script setup>
import { ref, onMounted } from 'vue';

const myInput = ref(null);

onMounted(() => {
  // myInput 是對 template 中 <input> 元素的引用
  myInput.value.focus();  // 聚焦到輸入框
});
</script>
⚠️ **GitHub.com Fallback** ⚠️