文章目錄
- 前言
- 一、組件的ref用法總結
- 總結
前言
之前學習過ref聲明響應式對象,前幾天讀代碼遇到了發懵的地方,詳細學習了一下才發現,用法還有很多,遂總結一下ref的用法備忘。
一、組件的ref用法總結
Vue3 中的 ref 是一種創建響應式引用的方式,它在Vue生態系統中扮演著重要角色。以下是Vue3中ref屬性及其相關API的幾個關鍵點:
創建響應式變量:使用 ref 函數可以創建一個響應式的數據引用,返回的對象包含 .value 屬性,該屬性既可以讀取也可以寫入,并且是響應式的。例如:
Javascript
1import { ref } from 'vue';
2
3const count = ref(0); // 創建一個響應式引用,初始值為0
4console.log(count.value); // 輸出0
5count.value++; // 改變值,這將觸發視圖更新
在模板中使用 ref:在模板中,可以使用 v-ref 或簡寫 ref 來給 DOM 元素或組件添加引用標識符。對于DOM元素:
<div ref="myDiv">Hello World</div>
然后在組件的 setup 函數內或者生命周期鉤子如 onMounted 中通過 ref 訪問到該元素:
onMounted(() => {console.log(myDiv.value); // 這將輸出對應的DOM元素
});// 注意,在setup函數中使用需要解構
setup() {const myDiv = ref<HTMLElement | null>(null);// ...
對于子組件,ref 則指向子組件的實例:
<MyChildComponent ref="childRef" />
動態 refs:在動態渲染的組件或循環列表中,可以使用動態 ref 名稱:
1<component v-for="(item, index) in items" :is="item.component" :key="index" :ref="`child${index}`" />
然后通過 getCurrentInstance() 獲取這些動態 ref:Javascript
1setup() {
2 const instance = getCurrentInstance();
3 const childrenRefs = computed(() => {
4 return instance.refs;
5 });
6 // ...
7}
組件間通信:通過 ref 可以方便地在組件之間傳遞并操作狀態,尤其適用于父子組件之間的通信。
(1)創建一個子組件 ChildComponent.vue:
<template><div><h2>{{ childMessage }}</h2><button @click="handleClick">點擊我</button></div>
</template><script>
import { ref, defineComponent } from 'vue';export default defineComponent({setup(props, { emit }) {const childMessage = ref('Hello from Child');const handleClick = () => {emit('child-clicked', 'Child component clicked!');};return {childMessage,handleClick,};},
});
</script>
(2)創建一個父組件 ParentComponent.vue,并使用 ref 屬性訪問子組件實例:
<!-- ParentComponent.vue --><template><div><h1>Parent Component</h1><ChildComponent ref="childRef" /><button @click="callChildMethod">Call Child Method</button></div>
</template><script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent,},setup() {const childRef = ref(null);function callChildMethod() {childRef.value.showMessage();}return {childRef,callChildMethod,};},
};
</script>
在這個示例中,我們在父組件的模板中使用了 ref 屬性,并將其值設置為 “childRef”。然后,在組合式 API 的 setup 函數中,我們創建了一個名為 childRef 的響應式引用,并將其初始值設置為 null。接著,我們定義了一個名為 callChildMethod 的方法,用于調用子組件的 showMessage 方法。當用戶點擊按鈕時,callChildMethod 方法會被調用,從而觸發子組件的 showMessage 方法并在控制臺輸出一條消息。
import { reactive, toRef } from 'vue';
2
3const state = reactive({ count: 0 });
4const countRef = toRef(state, 'count'); // 提取出count屬性的響應式引用
總結
總之,Vue3 的 ref 功能增強了Vue的響應式系統,使得開發者能夠更靈活地處理組件的狀態及組件間交互,同時提供了對DOM元素的直接訪問能力。
人總是在接近幸福時倍感幸福,在幸福進行時卻患得患失。