一、父组件向子组件传值:
- 在父组件中调用子组件时,使用v-bind将要传的值进行绑定
<com :parentmsg="msg"></com>
- 在子组件的props中,添加第一步中为接收父组件数据而定义的变量
props: ["parentmsg"]
- 子组件可使用 this.parentMsg 来调用父组件的数据 msg
二、子组件向父组件传值:
- 父组件中先定义一个方法a用来获取子组件的值
methods: { getChildMsg (data) { this.childMsg = data } },
- 在父组件中调用子组件时,将父组件的那个方法与子组件中的一个方法b绑定
<com :parentmsg="msg" @func='getChildMsg'></com>
- 在子组件中定义另一个方法c来处理用于绑定父组件方法的方法b,方法c 使用 $emit,第一个参数为方法b的名称,第二个参数为要传递给父组件的值
methods: { sendToParent () { this.$emit('func', this.msg) }, },
- 在子组件中用合适的方法调用 c 实现向父组件传值
created() { this.sendToParent() },
- 父组件可使用 this.childMsg 来调用子组件的数据 msg
实例代码:
1 <body> 2 <div id="app"> 3 <com :parentmsg="msg" @func='getChildMsg'></com> 4 <!-- 在父组件中可调用子组件中的数据 --> 5 <h2>{{childMsg}}</h2> 6 </div> 7 8 <template id="tmp"> 9 <div> 10 <!-- 在子组件中可调用父组件中的数据 --> 11 <h1>子元素模板---{{parentmsg}}</h1> 12 </div> 13 </template> 14 15 <script> 16 // 创建模板 17 let com = { 18 template: '#tmp', 19 data() { 20 return { 21 msg: "子组件中的数据" 22 } 23 }, 24 methods: { 25 sendToParent () { 26 this.$emit('func', this.msg) 27 }, 28 }, 29 created() { 30 this.sendToParent() 31 }, 32 props: ["parentmsg"] 33 } 34 35 // 创建Vue实例 36 let vm = new Vue({ 37 el: "#app", 38 data: { 39 msg: "父组件中的数据", 40 childMsg: '' 41 }, 42 methods: { 43 getChildMsg (data) { 44 this.childMsg = data 45 } 46 }, 47 components: { 48 com 49 } 50 }) 51 </script> 52 </body>