父传子
<template>
<div>
<h4>父组件--父传子</h4>
<p>
v-model 实时修改 text 的值,然后 change 监听到改变就会立马触发该方法获取里面的内容传递给 Text
</p>
<input type="text" v-model.lazy="text" @change="ChangeText" />
<childer :Text="text" />
</div>
</template>
<script>
import childer from "./childer";
export default {
name: "App",
data() {
return {
text: "",
};
},
components: {
childer,
},
methods: {
ChangeText(dataText) {
this.Text = dataText;
},
},
};
</script>
<style></style>
<template>
<div class="childer">
<h5>子组件</h5>
<div class="childerText">{{ Text }}</div>
</div>
</template>
<script>
export default {
name: "childer",
props: {
Text: String,
},
};
</script>
<style lang="scss">
.childer {
.childerText {
width: 200px;
height: 30px;
border: 1px solid #ccc;
}
}
</style>
子传父
<template>
<div>
<h3>父组件--子传父</h3>
<p>定义好修该父组件自己数据的方法,然后传给子组件传参修改</p>
<div class="parentData">{{ parentData }}</div>
<childer1 @getData="getData" />
</div>
</template>
<script>
import childer1 from "./childer1";
export default {
name: "Parent1",
data() {
return {
parentData: "",
};
},
components: {
childer1,
},
methods: {
getData(childerData) {
this.parentData = childerData;
},
},
};
</script>
<style lang="scss">
.parentData {
width: 200px;
height: 40px;
border: 1px solid #ccc;
}
</style>
<template>
<div>
<h5>子组件</h5>
<p>定义一个方法传值给父组件</p>
<input type="text" v-model="childerText" />
<button @click="setData">传递到父组件</button>
</div>
</template>
<script>
export default {
name: "childer1",
data() {
return {
childerText: "",
};
},
methods: {
setData() {
this.$emit("getData", this.childerText);
},
},
};
</script>
<style></style>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/749d57fabc43d3f2347cde35c0d44d4b.png#pic_center)