1.父子之间的通信方式
父给子传参:
在子组件上绑定一个参数,子组件通过props来接收这个参数
//父组件 <son :sonData="sonData"></son>//将sonData传给子组件 data() { return { sonData: "my son is so cool" }; }, //子组件 props: { sonData: { type: String, default: "good", }, },//通过props接收父组件的传递的参数,default是设置默认值,如果没有传递该参数则默认为“good”
子给父传参:
通过使用$emit给父组件传递一个方法,父组件在子组件上绑定@来接收这个方法
//子组件 this.$emit("emitFather", "my father is so cute ");//通过$emit将方法传递给父组件,第一个参数为自定义方法名,第二个为传递的参数。 //父组件 <son @getSon="emitFather"></son>//将子组件传递的方法重命名 methods: { getSon(letter) { console.log(letter); }, },
父调用子组件方法
父组件通过给子组件绑定ref,并且通过$refs来调用子组件的方法
//子组件 methods: { eat() { console.log("My father is going to take me to dinner"); }, }, //父组件 <son ref="mySon" ></son> mounted() { this.$refs.mySon.eat();//通过给子组件绑定ref来调用子组件的方法 },
2.兄弟或者子孙之间的传参
先创建一个bus.js的文件(为全局事件总线,如果想要进行传参在页面引用即可)
发送参数的组件SonOne.vue
//SonOne.vue import Bus from "@/utils/bus.js"; mounted() { var letter = "Please give me a piece of cake"; Bus.$emit("emitBrother", letter);//emitBrother为接受的方法名,letter为传递的参数 },
接收参数的组件SonTwo.vue
//SonTwo.vue import Bus from "@/utils/bus.js"; created() { Bus.$on("emitBrother", (data) => { console.log(data);//data为上个组件传递过来的参数 }); },
注意:Bus.$on应该在Bus.$emit之前,因为Bus.$on需要监听Bus.$emit是否发送,所以需要在它之前进行监听。