声明一个子组件,取名Son,使其可以接收父组件传递过来的值,也可以向父组件发送信息
props是儿子接收父亲信息的关键点
this.$emit是向父亲发送信息的关键
以下是子组件接收父亲信息一步,发送信息一步,很简单
<template>
<div>
<div>爸爸那传过来的参数:{{fromfather}}</div>
<!-- fromfather接收从父组件Father那收到的参数 -->
<button @click="toFather">触发emit</button>
<!-- toFather函数向父组件传值 -->
</div>
</template>
<script>
export default {
name: "Son",
data() {
return {
forfather: "thank u father"
//这是要传给父组件的信息
};
},
props: {
//父亲传过来的信息,我们要在props里初始化配置,对应接手信息一步
//type表示父亲传过来的信息的数据类型,default表示默认值
fromfather: {
type: String,
default: ""
}
},
methods: {
toFather() {
//接受信息一步
//通过this.$emit,有两个参数
//第一个fromchild是要和父亲对上的暗号,父亲那边也要用fromchild
//第二个是你要传达的信息
this.$emit("fromchild", this.forfather);
}
},
mounted() {}
};
</script>
接下来是父组件,父亲也要发送给儿子信息,然后接收儿子的信息
<template>
<div>
<Son :fromfather="msg" @fromchild="customize"></Son>
<div v:if="son_msg">{{son_msg}}</div>
<!-- 这里我们把子组件传过来的参数通过son_msg展示出来 -->
</div>
</template>
<script>
//调用你的子组件
import Son from "./son";
export default {
name: "Father",
//在componts里声明,你就可以使用了
components: {
Son
},
data() {
return {
son_msg: "",
//son_msg是我们拿到儿子的信息然后通过它展示出来
//用到的数据要在data里初始化配置
msg: "moshimoshi,this is father"
//msg为父亲给儿子的口信
};
},
methods: {
customize(sonmsg) {
//通过customize和我们设置的形参sonmsg,我们可以拿到儿子给爸爸的消息
//做进一步的逻辑处理
this.son_msg = sonmsg;
}
}
};
</script>
<Son :fromfather="msg" @fromchild="customize"></Son>
好好看看这一块
msg为父亲给儿子的信息
fromfather是传给儿子的参数命名,还记得吗,儿子得在props里配置这个fromfather
customize为本地自定义函数,取什么名字无所谓
fromchild是暗号,但是得跟你儿子的this.$emit的第一个参数,即暗号,要对得上就行