* `toRef`函數為源響應式對象上的某個屬性創建一個 ref 對象,二者內部操作的是同一個數據值,更新時二者是同步的。
* `toRef`與`ref`不同的是:ref 是拷貝了一份新的數據值單獨操作,更新時相互不影響。
* 應用:當要將某個`prop`的 ref 傳遞給復合函數時,toRef 很有用。
**1. 演示`toRef`與`ref`的不同**
```html
<template>
<!-- 4. 分別更新age和money并查看效果 -->
<h3>state: {{ state }}</h3>
<h3>age: {{ age }}</h3>
<h3>money: {{ money }}</h3>
<hr />
<button @click="updateAge">更新age</button>
<button @click="updateMoney">更新money</button>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRef } from "vue"
export default defineComponent({
setup() {
//1. 創建一個響應式對象
const state = reactive({
age: 5,
money: 100,
})
//2. 分別用toRef和ref將state.age屬性和state.money轉換為ref對象
const age = toRef(state, "age")
const money = ref(state.money)
//3. 更新age和money
const updateAge = () => {
age.value += 5
console.log(age.value)
console.log(state.age)
//age與state.age同步更新
}
const updateMoney = () => {
money.value += 10;
console.log(money.value)
console.log(state.money)
//只有money更新,state.money不會被更新
}
return {
state,
age,
money,
updateAge,
updateMoney,
}
}
})
</script>
```
效果如下,可見當更新 age 時,age 與 state.age 同步更新;當更新 money 時,只有 money 被更新,state.money 不會被更新。更新 state.age 則 age 也會同步更新的。

<br/>
**2. `toRef`的一個應用示例**
(1)父組件 *`src/components/LearnToRefParent.vue`*
```html
<template>
<h2>父組件</h2>
<!-- 4. 更新price并查看效果 -->
<h3>state: {{ state }}</h3>
<h3>price: {{ price }}</h3>
<button @click="update">更新</button>
<hr />
<!-- 5. 向子組件傳遞屬性price -->
<LearnToRefChild :price="price"></LearnToRefChild>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRef } from "vue";
import LearnToRefChild from "./LearnToRefChild.vue";
export default defineComponent({
setup() {
//1. 創建一個響應式對象
const state = reactive({
price: 90
})
//2. 用toRef將state.price轉換為ref對象
const price = toRef(state, 'price')
//3. 更新price
const update = () => {
price.value += 10
}
return {
state,
price,
update
}
},
components: {
LearnToRefChild,
}
})
</script>
```
(2)子組件 *`src/components/LearnToRefChild.vue`*
```html
<template>
<h2>子組件</h2>
<!-- 4. 觀看效果 -->
<h3>price: {{ price }}</h3>
<h3>length: {{ length }}</h3>
</template>
<script lang="ts">
import { computed, defineComponent, Ref, toRef } from "vue";
//2. 獲取字符串長度的函數,參數類型為Ref
function useGetLength(price: Ref) {
return computed(() => {
return price.value.toString().length
})
}
export default defineComponent({
setup(props) {
//3. 當函數要求的參數是一個Ref對象時,toRef的作用就體現出來了
const length = useGetLength(toRef(props, 'price'))
return {
length,
}
},
props: {
price: { //1. 從父組件傳遞過來的price屬性
type: Number,
required: true,
},
},
})
</script>
```
(3)效果。

- nodejs
- 同時安裝多個node版本
- Vue3
- 創建Vue3項目
- 使用 vue-cli 創建
- 使用 vite 創建
- 常用的Composition API
- setup
- ref
- reactive
- 響應數據原理
- setup細節
- reactive與ref細節
- 計算屬性與監視
- 生命周期函數
- toRefs
- 其它的Composition API
- shallowReactive與shallowRef
- readonly與shallowReadonly
- toRaw與markRaw
- toRef
- customRef
- provide與inject
- 響應式數據的判斷
- 組件
- Fragment片斷
- Teleport瞬移
- Suspense
- ES6
- Promise對象
- Promise作用
- 狀態與過程
- 基本使用
- 常用API
- async與await
- Axios