2024-12-12 Vue裡面的 ref 是什麼?

2024-12-12 Vue裡面的 ref 是什麼?

ref 是 Vue 3 Composition API 中的一個函式,用來建立可響應的變數。它允許你追蹤和反應數據的變化,並且可以直接用於模板或其他邏輯中。

為什麼使用 ref

在 Vue 中,數據變化時會自動更新相關的視圖,而 ref 提供了一種簡單的方式來建立這種響應式數據。當 ref 中的數據改變時,Vue 會自動更新與該數據相關聯的部分視圖。


如何使用 ref

基本語法:

1
2
3
import { ref } from 'vue';

const myVariable = ref(initialValue);
  • initialValueref 的初始值,可以是任意類型的數據(如字串、數字、物件、陣列等)。
  • myVariable.value:用來訪問或修改 ref 的值。

範例:簡單的響應數據

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
import { ref } from 'vue';

export default {
setup() {
const counter = ref(0); // 建立一個響應式數據,初始值為 0

const increment = () => {
counter.value += 1; // 修改 counter 的值
};

return { counter, increment }; // 返回以便模板中使用
},
};
</script>

<template>
<div>
<p>Counter: {{ counter }}</p> <!-- 當 counter 改變時,視圖會自動更新 -->
<button @click="increment">Increment</button>
</div>
</template>

ref 的特點

  1. 包裝響應式數據

    • ref 會將非物件類型(如字串、數字等)包裝為一個響應式對象。
    • 存取或改變數據時需使用 .value
    1
    2
    3
    4
    const count = ref(0);
    console.log(count.value); // 0
    count.value = 10;
    console.log(count.value); // 10
  2. 可用於物件或陣列

    • ref 的初始值是一個物件或陣列時,其內部屬性也會是響應式的。
      1
      2
      const user = ref({ name: 'Alice', age: 25 });
      user.value.name = 'Bob'; // 視圖自動更新
  3. 適合 DOM 元素引用

    • ref 不僅用於數據,也可以用來引用 DOM 元素。
    • setup 中,你可以用 ref 來存放一個 DOM 元素的引用。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <template>
    <input ref="inputRef" type="text" />
    </template>

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

    export default {
    setup() {
    const inputRef = ref(null); // 建立 DOM 元素的引用

    onMounted(() => {
    inputRef.value.focus(); // 在組件掛載後,讓 input 獲得焦點
    });

    return { inputRef };
    },
    };
    </script>
  4. 用於模板中的雙向綁定

    • 在表單中,ref 非常適合用來雙向綁定數據。
      1
      const message = ref('');
    1
    2
    <input v-model="message" />
    <p>{{ message }}</p>

ref vs reactive

Vue 提供兩種方式來創建響應式數據:refreactive

特性 ref reactive
適用場景 單一變數或簡單數據類型 複雜物件或多屬性數據
存取方式 使用 .value 可直接存取屬性
結構化數據(物件/陣列) 包裝後的物件,其內部屬性自動響應 整個物件是響應式的
語法簡潔性 更適合單一變數或 DOM 引用 更適合定義完整的響應式物件

範例:ref

1
2
const count = ref(0);
count.value += 1; // 使用 .value 更新值

範例:reactive

1
2
const state = reactive({ count: 0 });
state.count += 1; // 無需使用 .value

結論

  • ref 是 Vue 3 中強大的工具,用於建立簡單的響應式數據或引用 DOM 元素。
  • 在你處理單一變數(如數字、字串)或需要 DOM 元素引用時,推薦使用 ref
  • 如果你需要管理更複雜的物件結構(如整個表單的數據),可以考慮使用 reactive