組件通信
-
父子
-
props
-
$children
$children 父組件可以通過$children訪問子組件實現父子通信 this.$children[1].sendToChild1();
- $refs
this.$refs.child2.sendToChild1();
- listeners
包含了父作用域中不作爲 prop 被識別 (且獲取) 的特性綁定 ( class 和 style 除外)。當一個組件沒有 聲明任何 prop 時,這裏會包含所有父作用域的綁定 ( class 和 style 除外),並且可以通過 v- bind="$attrs" 傳入內部組件——在創建高級別的組件時非常有用。
// child:並未在props中聲明foo <p>{{$attrs.foo}}</p> // parent <HelloWorld foo="foo"/>
-
-
子父
- 自定義事件
-
兄弟
- $parent、 $root [兄弟節點之間可以通過共同祖輩搭橋]
// brother1 this.$parent.$on('foo', handle) // brother2 this.$parent.$emit('foo')
-
跨級
- provide/inject
-
任意組件
- vuex
- event Bus
export default 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) }); } } }
作用域插槽
- 匿名插槽
// comp1
<div>
<slot></slot>
</div>
// parent
<comp>hello</comp>
- 具名插槽 [將內容分發到子組件具體位置]
// comp2
<div>
<slot></slot>
<slot name="content"></slot>
</div>
// parent
<Comp2>
<!-- 默認插槽用default做參數 -->
<template v-slot:default>具名插槽</template> <!-- 具名插槽用插槽名做參數 -->
<template v-slot:content>內容...</template>
</Comp2>
- 作用域插槽[分發內容要用到子組件中的數據]
// comp3
<div>
<slot :foo="foo"></slot>
</div>
// parent
<Comp3>
<!-- 把v-slot的值指定爲作用域上下文對象 -->
<template v-slot:default="slotProps"> 來自子組件數據:{{slotProps.foo}} </template>
// 名爲footer的插槽
<template v-slot:footer="slotProps">{{slotProps.fc}}</template>
</Comp3>
組件實例化
- vue.extend
- vue.component
export default function create(Component, props) {
const Ctor = Vue.extend(Component)
const comp = new Ctor({
el: document.createElement('div'),
propsData: props
})
const $el = comp.$el;
document.body.appendChild($el);
Ctor.prototype.remove = () => {
const $el = comp.$el;
document.body.removeChild($el)
comp.$destroy();
}
// 方式二:借雞生蛋
const vm = new Vue({
render(h) {
return h(Component, { props })
}
}).$mount() // $mount()本質上將vdom=》dom
****
// 通過vm.$el獲取生成的dom
document.body.appendChild(vm.$el)
// 刪除函數
// 獲取組件實例
const comp = vm.$children[0]
comp.remove = () => {
document.body.removeChild(vm.$el)
vm.$destroy()
}
return comp
}
// 組件中使用