vue3实现双向数据绑定的3种写法:常规写法、v-model、defineModel
常规写法:
<!-- 父组件 -->
<template>
<button @click="data = 'Hello Vue3'">修改子组件数据</button>
<!-- 简写 -->
<!-- <child :data="data" @update="data = $event"/> -->
<child :data="data" @update="changeData"/>
</template>
<script setup>
import child from './components/child.vue'
import { ref } from 'vue'
const data = ref('Hello Vue2')
const changeData = (val) => {
data.value = val
}
</script>
<!-- 子组件 -->
<template>
<div>{{ data }}</div>
<button @click="emit('update', '你好,世界!')">修改父组件的数据</button>
</template>
<script setup>
defineProps({
data: String
})
const emit = defineEmits('update')
</script>
v-model:
<!-- 父组件 -->
<template>
<button @click="data = 'Hello Vue3'">修改子组件数据</button>
<child v-model="data"/>
</template>
<script setup>
import child from './components/child.vue'
import { ref } from 'vue'
const data = ref('Hello Vue2')
</script>
<!-- 子组件 -->
<template>
<div>{{ modelValue }}</div>
<button @click="emit('update:modelValue', '你好,世界!')">修改父组件的数据</button>
</template>
<script setup>
defineProps({
modelValue: String
})
const emit = defineEmits('update')
</script>
如果要绑定多个变量:
<!-- 父组件 -->
<template>
<button @click="data1 = 'Hello Vue3'">修改子组件数据</button>
<button @click="data2 = 'Hello Vue3'">修改子组件数据</button>
<child v-model:data1="data1" v-model:data2="data2"/>
</template>
<script setup>
import child from './components/child.vue'
import { ref } from 'vue'
const data1 = ref('Hello Vue')
const data2 = ref('Hello Vue')
</script>
<!-- 子组件 -->
<template>
<div>{{ data1 }}</div>
<div>{{ data2 }}</div>
<button @click="emit('update:data1', '你好,世界!')">修改父组件的数据</button>
<button @click="emit('update:data2', '你好,世界!')">修改父组件的数据</button>
</template>
<script setup>
defineProps({
data1: String,
data2: String
})
const emit = defineEmits('update')
</script>
defineModel:(注:仅支持vue3.2.0及以上版本)
<!-- 父组件 -->
<template>
<button @click="data = 'Hello Vue3'">修改子组件数据</button>
<child v-model="data"/>
</template>
<script setup>
import child from './components/child.vue'
import { ref } from 'vue'
const data = ref('Hello Vue')
</script>
<!-- 子组件 -->
<template>
<div>{{ modelValue }}</div>
<button @click="modelValue = '你好,世界!' ">修改父组件的数据</button>
</template>
<script setup>
import { defineModel } from 'vue'
const modelValue = defineModel()
</script>
绑定多个变量:
<!-- 父组件 -->
<template>
<button @click="data1 = 'Hello Vue3'">修改子组件数据</button>
<button @click="data2 = 'Hello Vue3'">修改子组件数据</button>
<child v-model:data1="data1" v-model:data2="data2"/>
</template>
<script setup>
import child from './components/child.vue'
import { ref } from 'vue'
const data1 = ref('Hello Vue')
const data2 = ref('Hello Vue')
</script>
<!-- 子组件 -->
<template>
<div>{{ data1 }}</div>
<div>{{ data2 }}</div>
<button @click="data1 = '你好,世界!' ">修改父组件的数据</button>
<button @click="data2 = '你好,世界!' ">修改父组件的数据</button>
</template>
<script setup>
import { defineModel } from 'vue'
const data1 = defineModel("data1")
const data2 = defineModel("data2")
</script>