1,父组件向子组件传参函数
<template> <div> I am a 'a' component <com-b :prop-data="0" msgfromfather="I am your father"></com-b> </div> </template> <script> import comB from './b' export default { components: {comB}, props: ['propData'] } </script>
Prop 是你能够在组件上注册的一些自定义特性。当一个值传递给一个 prop 特性的时候,它就变成了那个组件实例的一个属性。this
<template> <div> <div>{{msg}}</div> <div>{{msgfromfather}}</div> <button v-on:click="onClickMe">click me </button> </div> </template> <script> export default{ data: function(){ return { msg: 'this is Part B!' } }, props: [ 'msgfromfather' //注册父组件传递的消息 ], methods: { onClickMe: function(){ console.log(this.msgfromfather)//能够直接调用 } } } </script>
2,子组件向父组件传递消息spa
方法一:利用自定义事件 on和emitcode
在父组件中自定义函数v-on:child-tell-me="listenToMyBoy"component
在子组件中触发定义的事件this.$emit("child-tell-me", this.msg), msg就是子组件传递的信息blog
在父组件实现以前定义的方法‘listenToMyBoy’事件
//父组件 <template> <div> I am a 'a' component <p>Child component b tells me: {{childWords}}</p> <com-b :prop-data="0" msgfromfather="I am your father" v-on:child-tell-me="listenToMyBoy"></com-b> </div> </template> <script> import comB from './b' export default { data: function(){ return { 'childWords': '' //要在页面使用子组件传递的信息,须要声明一个参数 } }, components: {comB}, props: ['propData'], methods: { listenToMyBoy: function(msg){ this.childWords = msg;//信息传递给声明的参数 } } } </script>
//子组件
<template> <div> <div>{{msg}}</div> <div>{{msgfromfather}}</div> <button v-on:click="onClickMe">click me </button> </div> </template> <script> export default{ data: function(){ return { msg: 'this is Part B!' } }, props: [ 'msgfromfather' ], methods: { onClickMe: function(){ //console.log(this.msgfromfather) this.$emit("child-tell-me", this.msg) } } } </script>
若是是跨多层父子组件通讯的话,$emit
并无什么用。ip