本文实例讲述了vuejs中父子组件之间通信方法。分享给大家供大家参考,具体如下:txe免费资源网
一、父组件向子组件传递消息
// Parent.vue
import VChild from './child.vue'
export default {
components: {
VChild
},
data () {
return {
// 父组件将message作为参数传入子组件中
message: '来自父组件消息'
}
}
}
// Child.vue
child
{{ msg }}
export default {
// 通过props定义外部系统可以传入的参数
// 定义了一个msg变量,类型是String,默认是空字符串
props: {
msg: {
type: String,
default: ""
}
}
}
// 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
}
]
})
二、子组件向父组件传递消息
// Parent.vue
import VChild from './child.vue'
export default {
components: {
VChild
},
data () {
return {
// 父组件将message作为参数传入子组件中
message: '来自父组件消息'
}
},
methods: {
childNotify (params) {
console.log(params)
}
}
}
// Child.vue
child
{{ msg }}
export default {
// 通过props定义外部系统可以传入的参数
// 定义了一个msg变量,类型是String,默认是空字符串
props: {
msg: {
type: String,
default: ""
}
},
methods: {
notifyParent () {
var params = {
m: 1,
n: 2
}
// 子组件以事件的形式通知父组件(需要使用$emit方法,第一个参数,事件名称;第二个事件附带的参数)
this.$emit('childNotify', params)
}
}
}
参考:https://jingyan.baidu.com/article/455a99505b639da1662778e1.htmltxe免费资源网
希望本文所述对大家vue.js程序设计有所帮助。txe免费资源网