父
<template>
<TestCom v-model="test1" v-model:test2="test2">TestCom>
<h1>{{test1}}测试1h1>
<h1>{{test2}}测试2h1>
template>
<script setup>
import { ref, reactive } from 'vue'
const test1 = ref('')
const test2 = ref('')
script>
子(setup语法糖)
<template>
<input v-model="message" @input="changeInfo(message)" />
<input v-model="message2" @input="changeInfo2(message2)" />
template>
<script setup>
import { ref, watch } from 'vue';
// 此处引入
const emit = defineEmits(['update:modelValue', 'update:test2'])
const props = defineProps({
// 父组件 v-model 没有指定参数名,则默认是 modelValue
modelValue:{
type:String,
default: 'test'
},
test2: {
type: String,
default: 'aaa'
}
})
let message = ref('123')
let message2 = ref('456')
// 因为props.modelValue、props.test2是非引用类型,改变时,需要监听,对响应式数据重新赋值
watch(()=> props.modelValue,() => {message.value = props.modelValue})
watch(()=> props.test2,() => {message2.value = props.test2})
// 数据双向绑定
const changeInfo = (info) => {
emit('update:modelValue', info)
}
const changeInfo2 = (info2) => {
emit('update:test2', info2)
}
script>
子(常规写法)
<script>
import { ref, watch } from 'vue';
export default {
props: {
// 父组件 v-model 没有指定参数名,则默认是 modelValue
modelValue:{
type:String,
default: 'test'
},
test2: {
type: String,
default: 'aaa'
}
},
setup(props, { emit }) {
let message = ref('123')
let message2 = ref('456')
// 因为props.modelValue、props.test2是非引用类型,改变时,需要监听,对响应式数据重新赋值
watch(()=> props.modelValue,() => {message.value = props.modelValue})
watch(()=> props.test2,() => {message2.value = props.test2})
// 数据双向绑定
const changeInfo = (info) => {
emit('update:modelValue', info)
}
const changeInfo2 = (info2) => {
emit('update:test2', info2)
}
return {
message, message2, changeInfo, changeInfo2
}
}
}
script>