props 父->子传值 用属性
parent
<child :faData = '来自父亲'></child>
child
props:{
faData:{
type:String,
default:""
}
}
子->父 用自定义事件
child
this.$emit('add',good)
parent
<child @add='cartAdd($event)'></child>
任意两个组件之间值传递
main.js 注册
Vue.prototype.$bus = new Vue()
parent
<template>
<child1 ></child1>
<child2 ></child2>
<template>
child1
this.$bus.$on('event-from-child2',msg=>{
console.log(msg)
})
child2
this.$bus.$emit('event-from-child2','some msg from child2')
parent 里 child1 和child2 通信
<child1></child1>
<child2></child2>
child1
mounted(){
this.$parent.$on('event-from-child1',msg=>{
console.log(msg)
})
}
child2
mounted(){
this.$parent.$emit('event-from-child2','some msg from child2')
}
父组件可以通过$children 访问子组件实现父子通信 $children 拿到的是一个子组件数组,不能保证子元素顺序
parent
<button @click='goHome'></button>
goHome(){
this.$children[0].eat()
}
child1
eat(){
console.log('马上回')
}
child2
包含了父作用域中不作为prop被识别(且获取)的特性绑定(class 和style 除外).当一个组件没有声明任何prop时,这里会包含所有父作用域的绑定(class 和 style 除外),并且可以通过v-bind = "$attrs" 传入内部组件——在创建高级别的组件时非常有用
parent
<child foo='foo' @click='onClick'></child>
onClick(){
console.log("来自parent的回调函数处理")
}
child
<p v-on='$listeners'>{{$attrs.foo}}</p>
并未在props 中声明foo
v-on='$listeners' 运行会被展开并监听(在parent里监听)
child2
获取子节点引用 | 访问普通的dom 元素
能够实现祖先和后代之间传值
ancestor
provide(){
return {foo:'foo'}
}
descendant
inject:['foo']
可以起别名
inject:{bar:{from:'foo'}}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。