1、话不多说直接看代码:新建一个helloworld的子组件内容如下
<template>
<input :value="modelValue" @input="inputChange">
</template>
<script setup>
const porps = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const inputChange=(e)=>{
emit('update:modelValue', e.target.value)
}
</script>
<style scoped lang="less">
input {
width: 200px;
height: 30px;
border: 1px solid black;
}
</style>
2、在父组件中导入并使用如下:
<template>
<HelloWorld v-model="num" ></HelloWorld>
</template>
<script setup>
import HelloWorld from "@/components/HelloWorld.vue";
import {ref, watch} from "vue";
const num = ref(0)
watch(num, (newVal)=>{
// 监听看是否父组件改变了
console.log('newVal: ', newVal);
})
<script>
3、效果如下: