分别介绍一种常用的父组件向子组件传值和子组件向父组件传值的方法。
首先建立组件father.vue和child.vue作为示例的基础,在子组件中的prop定义:希望父组件传递并在子组件使用的数据,父组件在child标签中传递参数,既可以使用v-bind传递父组件的动态数据,也可以直接传递静态的值。 father.vue
//父组件 <template> <div> <h1>我是父组件!</h1> <child :Msg="fatherMsg" nickname="明明"></child> </div> </template> <script> import Child from '../components/child.vue' export default { data(){ return { fatherMsg: "父亲拍了拍你" }; }, components: {Child}, } </script>child.vue
//子组件 <template> <h3>我是子组件!</h3> </template> <script> export default { props: { title: {//声明一个自定义的属性` type: String, default: "这里写名字" }, Msg: { type: String, default: "这里写刚才父亲的动作" }, } } </script>子组件则通过emit函数向父组件传递数据,父子均在method里写相应的传递和接收函数,并在引入标签使用v-on调用。 father.vue
//父组件 <template> <div> <h1>我是父组件!</h1> <child @childMsg="showMsg"></child> </div> </template> <script> import Child from '../components/child.vue' export default { data(){ return { }; }, components: {Child}, methods:{ showMsg(message){ console.log(message) } } } </script>child.vue
//子组件 <template> <h3>我是子组件!</h3> </template> <script> export default { props: { }, mounted:{ function(){ this.$emit('childMsg','我哭了'); } } } </script>另外,如果父组件需要调用子组件的属性和方法,可以采用$ref的形式引用子组件,兄弟组件的数据传递也可采用emit方法,不过另一个兄弟需要定义对应的on方法,并建立eventbus。
参考:vue父子组件间通信传值讲解props、emit、refs