📢 本文由 gemini-3-flash-preview 翻譯
定義 Options API 選項
Vue 3.3 引入了 defineOptions() 巨集函式,用來定義 Options API 的選項,除了 props, emits, expose, slots 以外(因為已有對應的 define 函式)。
1
2
3
4
5
6
| <script setup>
defineOptions({
name: 'LoginIndex',
// ...
})
</script>
|
name 的作用:
- 偵錯方便 - 在開發者元件工具中會顯示
name 的值 - 遞迴元件 - 元件內部呼叫自己時可以使用自己的
name 值 <keep-alive> 快取可以透過 name 決定是否快取
父子元件雙向資料綁定
原先為了實作雙向資料綁定較為麻煩。
父元件中:
1
2
3
4
5
6
7
8
9
10
11
| <script setup>
import { ref } from 'vue';
import inputCom from './components/input-com.vue';
const msg = ref("a msg from father")
</script>
<template>
<inputCom v-model="msg"></inputCom>
<div>{{ msg }}</div>
</template>
|
子元件中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| <script setup>
defineProps({
modelValue: String
})
const emit = defineEmits(['update:modelValue'])
</script>
<template>
<div>
<input
type="text"
:value="modelValue"
@input="e => emit('update:modelValue', e.target.value)"></input>
</div>
</template>
|
而使用了 defineModel() 函式後會更加方便,子元件可以寫成:
1
2
3
4
5
6
7
8
9
10
11
12
| <script setup>
const modelValue = defineModel()
</script>
<template>
<div>
<input
type="text"
:value="modelValue"
@input="e => modelValue = e.target.value"></input>
</div>
</template>
|