单一值传递
父组件
< template> < div > < h1> v- model实现父子组件通讯< / h1> < hr> < child1 v- model= "num" > < / child1> < ! -- 上下两个是等价的 -- > < child1 : modelValue= "num" @update: modelValue= "handle" > < / child1> < / div>
< / template> < script setup>
import { ref} from 'vue'
import child1 from './child1.vue' ;
let num = ref ( 0 ) ;
const handle = ( value ) => { num. value = value
}
< / script>
子组件
< template> < div> < h1> 我是子组件< / h1> < ! -- 父组件传过来的值 -- > < h3> { { modelValue } } < / h3> < button @click= "$emit('update:modelValue', modelValue+1)" > 修改父组件的值< / button> < / div>
< / template> < script setup>
let props = defineProps ( [ 'modelValue' ] )
const $emit = defineEmits ( [ 'update:modelValue' ] )
< / script>
多个v-model实现父子组件传值
父组件
< template> < div > < h1> v- model实现父子组件通讯< / h1> < hr> < child1 v- model: firstnum= "num1" v- model: secondnum= "num2" > < / child1> < / div>
< / template> < script setup>
import { ref} from 'vue'
import child1 from './child1.vue' ;
let num1 = ref ( 0 ) ;
let num2 = ref ( 0 ) ;
< / script> < style lang= "scss" scoped> < / style>
子组件
< template> < div> < h1> 我是子组件< / h1> < ! -- 父组件传过来的值1 -- > < h3> { { firstnum } } < / h3> < ! -- 父组件传过来的值2 -- > < h3> { { secondnum } } < / h3> < button @click= "handler" > 修改父组件的值< / button> < / div>
< / template> < script setup>
let props = defineProps ( [ 'firstnum' , 'secondnum' ] )
const $emit = defineEmits ( [ 'update:firstnum' , 'update:secondnum' ] )
const handler = ( ) => { $emit ( 'update:firstnum' , props. firstnum+ 1 ) $emit ( 'update:secondnum' , props. secondnum+ 4 )
}
< / script>