0%

Ref and Reactive in Vue

ref()

ref() is in composition API.

What does it do?

Takes an value as its inner value and returns a reactive and mutable ref object, which has a single property .value that points to the inner value.

explain

1.The ref object is mutable you can assign new values to .value.

2.It is also reactive any read operations to .value are tracked, and write operations will trigger associated effects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<template>
<div>
<h2>Ref Example</h2>
<p>Count: {{ count.value }}</p>
<button @click="increment">Increment</button>
<p>Message: {{ message }}</p>
<button @click="changeMessage">Change Message</button>
</div>
</template>

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

// 1. Create a mutable ref object
const count = ref(0);

// 2. Watch for changes (reactive)
watch(count, (newVal) => {
console.log(`Count changed to: ${newVal}`);
});

// Function to increment the count
const increment = () => {
count.value++; // Mutating the value
};

// Message to demonstrate tracking
let message = "Initial Message";

// Function to change the message
const changeMessage = () => {
message = "Message Changed!"; // Change message, not tracked by ref
console.log(`Message changed to: ${message}`);
};
</script>

<style>
button {
margin-right: 10px;
}
</style>

Note

1.The count is created as a ref, and you can modify its value using count.value++. This shows that .value is mutable.

2.Changing message directly doesn’t trigger reactivity because it isn’t a ref. This highlights that only ref objects are tracked reactively.

what can you pass into ref()

primitive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script setup>
import { ref } from "vue";

const count = ref(0);
const handleCountIncrement = () => {
count.value++;
};
</script>

<template>
<div class="main">
<p>count: {{ count }}</p>
<button @click="handleCountIncrement">count++</button>
</div>
</template>

reference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script setup>
import { ref } from "vue";
const product = ref({ price: 0 });

const changeProductPrice = () => {
product.value.price += 10;
};
</script>

<template>
<div class="main">
<p>price: {{ product.price }}</p>
<button @click="changeProductPrice">修改产品价格</button>
</div>
</template>

Regardless of whether the value of the primitive data type or the value of the reference data type is passed to the ref function, the returned object is constructed by the RefImpl class, but the difference is the value in the object:

如果 ref 函数参数传递的是原始数据类型的值,那么 value 是一个原始值
如果 ref 函数参数传递的是引用数据类型的值,那么 value 是一个 Proxy 对象