[TOC]
# 1. ref 創建響應式數據
* `ref`是一個函數,返回的是一個`Ref`對象。
* 作用:用來定義一個響應式的數據。
* 一般用來定義一個基本類型的響應式數據,如果想要定義一個對象類型的響應式數據可以使用函數`reactive`。
```html
<template>
<!-- 6. 在模板中調用count的值,直接調用count即可,不能調用count.value -->
<h1>{{ count }}</h1>
<button @click="updateCount">更新count</button>
</template>
<script lang="ts">
// 1. 引入 ref 函數
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
// 2. 調用 ref 函數定義一個響應數據
const count = ref(0);
// 3. 定義一個更新count屬性的方法
function updateCount() {
count.value++;
// 4. 在js代碼中以 count.value 調用來獲取count的值
console.log(count.value);
}
return {
// 5. 將他們放置在setup的返回對象中
count,
updateCount,
};
},
});
</script>
```

<br/>
# 2. ref 獲取頁面元素
`ref`函數可以獲取頁面中已經加載完畢的元素。
```html
<template>
<!-- 1. 在標簽中使用 ref 屬性綁定一個數據 -->
<input type="text" id="demo" ref="inputRef" />
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
export default defineComponent({
setup() {
//2. 調用ref創建初始值為null的響應數據
const inputRef = ref < HTMLElement | null > (null);
onMounted(() => {
//3. 在生命周期函數onMounted頁面已經渲染好了,可以在這里拿到頁面的元素
console.log(inputRef.value);
//<input type="text" id="demo">
//表示標簽存在時,就讓該標簽自動獲取焦點
inputRef.value && inputRef.value.focus();
});
return {
inputRef,
};
},
});
</script>
```
- 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