一、新建文件
1.新建文件father.vue
和children.vue
放在同意目录下;
二、代码如下:
1.father.vue
的代码:
<template>
<div class="fater">
<h1>我是父组件</h1>
<h2>我是childern传过来的数据:{
{
ctofValue}}</h2>
<children :ftoc="ftocValue" ref="child" @pFunc="pFunc"></children>
</div>
</template>
<script>
import children from "./children";
export default {
components: {
children: children
},
data() {
return {
ftocValue: "父传子值",
ctofValue: "",
implementValue: "父组件执行子组件方法"
};
},
methods: {
pFunc(value) {
this.ctofValue = value;
},
childrenFun() {
this.$refs.child.childFun("父组件执行子组件方法");
}
},
mounted() {
this.childrenFun();
}
};
</script>
<style>
.fater {
border: 5px solid red;
}
</style>
2.children.vue
的代码:
<template>
<div class="children">
<h1>我是子组件</h1>
<h3>我是father传过来的数据:{
{
ftoc}}</h3>
<h3>我是father执行子组件的childFun方法传过来的数据:{
{
imValue}}</h3>
</div>
</template>
<script>
export default {
props: {
ftoc: String
},
data() {
return {
msg: "子传父值",
imValue: ""
};
},
methods: {
sendMes() {
this.$emit("pFunc", this.msg);
},
childFun(value) {
this.imValue = value;
}
},
mounted() {
this.sendMes();
}
};
</script>
<style>
.children {
border: 5px solid red;
}
</style>
三、代码运行网页示例如下:
四、解析:
本示例演示了,父子组件传值,父组件执行子组件方法,子组件执行父组件方法的输出结果和过程。
父组件给子组件传值:通过在father
文件中组件绑定值ftoc
传值给子组件,然后子组件通过props
接收并输出数据,使子组件可以使用他。
子组件给父组件传值(子组件执行父组件中的方法):通过在father
文件中监听事件pFunc
然后去执行pFunc
,子组件通过$emit
去执行pFunc
来达到执行父组件事件并传值的效果。
父组件执行子组件的方法:在father
页面中给子组件声明ref
,通过$ref.
(ref
的值)来确定执行那个子组件中的方法。