vuejs中父子组件之间通信
![](http://oy1lwtkfl.bkt.clouddn.com/2018-07-12_212020.jpg)
一、父组件向子组件传递消息
// Parent.vue
<template>
<div class="parent">
<v-child :msg="message"></v-child>
</div>
</template>
<script>
import VChild from './child.vue'
export default {
components: {
VChild
},
data () {
return {
message: '来自父组件消息'
}
}
}
</script>
// Child.vue
<template>
<div class="child">
<h1>child</h1>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
default: ""
}
}
}
</script>
// router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Parent from '@/test/Parent'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/parent',
component: Parent
}
]
})
![](http://oy1lwtkfl.bkt.clouddn.com/2018-07-12_210312.jpg)
二、子组件向父组件传递消息
// Parent.vue
<template>
<div class="parent">
<v-child :msg="message" @childNotify="childNotify"></v-child>
</div>
</template>
<script>
import VChild from './child.vue'
export default {
components: {
VChild
},
data () {
return {
message: '来自父组件消息'
}
},
methods: {
childNotify (params) {
console.log(params)
}
}
}
</script>
// Child.vue
<template>
<div class="child" @click="notifyParent">
<h1>child</h1>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
default: ""
}
},
methods: {
notifyParent () {
var params = {
m: 1,
n: 2
}
this.$emit('childNotify', params)
}
}
}
</script>
![](http://oy1lwtkfl.bkt.clouddn.com/2018-07-12_21-13-02GIF.gif)
vuejs如何实现父子组件之间通信
源代码:源代码下载