父組件=>子組件
props
//child
props: ["message"],
//parent
<HelloWorld message="hello world"></HelloWorld>
特性$attrs
//child里沒有在props里聲明foo,可以用如下方式取
this.$attrs.foo
//parent
<HelloWorld foo="foo"></HelloWorld>
問題1:props和$attrs的區(qū)別
props需要聲明才能取到值,子類需要主動接收屬性
$attrs不需要聲明可以取到值,子類不用主動接收屬性,會直接放在子類根元素上。在props里聲明的屬性不會在$attrs里取到
引用refs
//parent 想修改子組件里的xx值
<HelloWorld foo="foo" ref='fx'></HelloWorld>
this.$refs.fx.xx='xxxx'
子元素$children
// parent
this.$children[0].xx = 'xxx'
問題2:$refs和$children 的區(qū)別
$refs元素或者組件標(biāo)簽上添加ref屬性指定一個引用信息,引用信息將注冊在父組件的$refs對象上,使用$ref來指向dom元素或者組件實例,
需要注意:
$refs不能在created生命周期中使用?因為在組件創(chuàng)建時候?該ref還沒有綁定元素?
如果想在method中使用,使用 this.$nextTick(() => {}) 等頁面渲染好再調(diào)用,這樣就可以了
$children 訪問子組件實例,返回的是一個子組件數(shù)組 因為是異步,所以不保證順序的,
子組件=>父組件
//child
this.$emit('addTest',message)
//parent
<Cart v-on:addTest="cartAdd"></Cart>
兄弟組件:通過共同父輩組件
通過共同的祖輩組件搭橋,$parent或$root。
// brother1
this.$parent.$on('foo', handle)
// brother2this.$parent.$emit('foo')
祖先和后代之間
由于嵌套層數(shù)過多,傳遞props不切實際,vue提供了 provide/inject API完成該任務(wù)
provide/inject:能夠?qū)崿F(xiàn)祖先給后代傳值
// ancestor
provide() {? ? return {foo: 'foo'}
}
// descendant
inject: ['foo']
任意兩個組件之間:
事件總線 或 vuex事件總線:創(chuàng)建一個Bus類負責(zé)事件派發(fā)、監(jiān)聽和回調(diào)管理
// Bus:事件派發(fā)、監(jiān)聽和回調(diào)管理
class Bus{
constructor(){
this.callbacks = {}}
$on(name, fn){
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn) }
$emit(name, args){
if(this.callbacks[name]){ this.callbacks[name].forEach(cb => cb(args)) } }
} // main.js Vue.prototype.$bus = new Bus() // child1 this.$bus.$on('foo', handle) // child2 this.$bus.$emit('foo')