一、需要实现的需求:
子组件输入框的数据发生改变,父组件的数据跟着实时改变;
父组件的数据发生改变,子组件的数据跟着实时改变。
二、实现思路:
1、(1)在父组件引入子组件。(2)子组件在父组件当成标签使用时使用v-model来绑定数据
2、(1)当子组件输入框的数据发生改变时,触发父组件的input事件,并把输入框的数据传给父组件。
(2)当子组件接收到父组件传过来的value值时,实时显示在页面。
三、代码
父组件代码:Mine.vue
<template>
<div class="page" id="mine">
<h2>我是父组件</h2>
<p>接收到子组件传过来的数据:{{ myVal }}</p>
<one-com v-model="myVal"></one-com>
</div>
</template>
<script>
import One from "../components/One";
export default {
name: 'mine',
components: {
"one-com": One
},
data() {
return {
myVal: ''
}
}
}
</script>
<style scoped>
.page {
background: darkcyan;
}
</style>
子组件代码:One.vue
<template>
<div>
<br />
<hr />
<br />
<h2>我是子组件</h2>
<p>接收到父组件传过来的数据:{{ value }}</p>
<br />
<input type="text" @input="clickAction()" ref="in" placeholder="请输入">
</div>
</template>
<script>
export default {
props: ['value'],
methods: {
clickAction() {
this.$emit('input', this.$refs.in.value);
}
}
}
</script>
<style scoped></style>
四、查看页面效果:
![](https://img-blog.csdnimg.cn/img_convert/ed8117fc868514e15d088a4e0e43ec60.png)