咱们在进行vue开发时会将公共的部分进行抽象,而后生成一个独立的组件,这个组件能够被其它页面引用,若是但愿有交互的动做就设计到了值的传递,或者方法的回调等问题,这一次咱们主要来讲一下父组件和子组件的交互。html
子组件,经过定义了prods,而后能够实现从父组件向子组件的传递:vue
<template> <div id="app"> 这是自定义的组件:{{myMessage}} <button @click="childClick">调用父组件的方法</button> </div> </template> <script> export default { name: "testComponent", props: ["myMessage"], data() { return { message: "hello world", myNum: 37, myStr: "lind" }; }, methods: { childClick() { console.log("调用childClick"); this.$emit("abcClick", this.myNum, this.myStr); } } }; </script>
父组件/页面,直接为这个prods赋值便可,注意若是JS里props名称是小驼峰,在html须要用中线来代替app
<testComponent my-message="hello"></testComponent> <script> import testComponent from "@/components/testComponent"; export default { name: "test-grammer", props: { //接收父组件传递过来的参数 }, components: { testComponent } } </script>
在父页面绑定子组件的方法,而后子组件在某个时机去触,这就造成了在子组件里调用父组件的方法,使用了$emit来实现this
<button @click="childClick">调用父组件的方法</button> <script> export default { name: "testComponent", methods: { childClick() { this.$emit("abcClick", this.myNum, this.myStr); } } }; </script>
在父页面中去绑定这个abcClick事件
就能够了,当在子组件调用这个childClick事件时,绑定了abcClick的方法将会被一块儿回调设计
<testComponent @abcClick="sayHello"></testComponent> <script> import testComponent from "@/components/testComponent"; export default { name: "test-grammer", methods: { sayHello(Num, Str) { console.log("hello world~~" + Num + Str); } }, }; </script>