3.3 版之後的 defineModel - daniel-qa/Vue GitHub Wiki
相对于 defineProps + defineEmits 的简化
<script setup>
import { defineProps, defineEmits } from 'vue'
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>
<script setup>
const modelValue = defineModel()
</script>
- 子組件(ChildComponent.vue)
子組件一樣是用 v-model 綁定 ref 變數,使用 defineModel 宣告,( ref 要加 .value 在 script 中取值)
<template>
<el-input v-model="modelValue" placeholder="請輸入內容"></el-input>
</template>
<script setup>
const modelValue = defineModel(); // 定義 v-model 綁定
</script>
- 父組件(ParentComponent.vue)
父組件,只要宣告 ref(),和用 v-model 綁定即可
<template>
<ChildComponent v-model="inputValue" />
<p>當前輸入:{{ inputValue }}</p>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const inputValue = ref(''); // 父組件中的數據
</script>
這樣的寫法讓父子組件之間的數據綁定變得更加簡單清晰,直接使用 defineModel 管理 v-model
綁定多個變數的範例:
- 子組件(ChildComponent.vue)
<template>
<div>
<el-input v-model="name" placeholder="請輸入姓名"></el-input>
<el-input v-model="age" placeholder="請輸入年齡" type="number"></el-input>
</div>
</template>
<script setup>
const name = defineModel('name'); // 綁定 name
const age = defineModel('age'); // 綁定 age
</script>
- 父組件(ParentComponent.vue)
<template>
<ChildComponent v-model:name="userName" v-model:age="userAge" />
<p>姓名:{{ userName }}</p>
<p>年齡:{{ userAge }}</p>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const userName = ref(''); // 綁定的姓名
const userAge = ref(null); // 綁定的年齡
</script>
這樣就能在 defineModel 中輕鬆處理多個數據綁定了