废话不多说直接上代码
1、父组件的代码
<template>
<div class="">
<my-input @blur="change" v-model="search"></my-input>
</div>
</template>
<script>
import myInput from "../components/myInput.vue";
import { ref } from "vue";
export default {
setup() {
let search = ref(""); // 组件的value
// 失去焦点触发事件
function change() {
console.log(search.value);
}
return {
search,
change,
};
},
components: { myInput },
};
</script>
<style lang="scss" scoped></style>
2、子组件的代码 创建组价 myInput 在父组件引入
<template>
<div class="header">
<input type="text" @input="input" @blur="blur" :value="modelValue" />
</div>
</template>
<script>
export default {
props: {
modelValue: String, // v-model绑定的属性值
},
setup(props, { emit }) {
function input(e) {
// @input 事件 每打一个字就会触发一下
console.log(e.target.value); // 事件对象
emit("update:modelValue", e.target.value); // 传递的方法
//vue3中使用了modelValue来替代value
//也就是说vue3中,value改成了modelValue,input方法了改成update:modelValue
}
function blur() {
// 通过子传父触发事件
emit("blur");
}
return {
input,
blur,
};
},
components: {},
};
</script>
<style lang="scss" scoped>
.header {
width: 100%;
height: 40px;
background-color: rgb(207, 203, 203);
}
</style>