1. 程式人生 > 其它 >1-Vue元件化實戰【進階】

1-Vue元件化實戰【進階】

目標 1. 深入理解Vue的元件化機制 2. 掌握Vue元件化常用技術 3. 能夠設計並實現多種型別的元件 4. 加深對一些vue原理的理解 5. 學會看開源元件庫原始碼

知識點 1. 元件通訊方式盤點 2. 元件複合 3. 遞迴元件 4. 元件建構函式和例項 5. 渲染函式 6. 元件掛載

元件化

vue元件系統提供了一種抽象,讓我們可以使用獨立可複用的元件來構建大型應用,任意型別的應用界 面都可以抽象為一個元件樹。元件化能提高開發效率,方便重複使用,簡化除錯步驟,提升專案可維護 性,便於多人協同開發。

元件通訊常用方式

props

eventbus

vuex

自定義事件($emit)

邊界情況 $parent $children $root $refs provide/inject

非prop特性 $attrs $listeners

元件通訊

props

父給子傳值

// child
props: { msg: String }
// parent
<HelloWorld msg="Welcome to Your Vue.js App"/>

自定義事件

子給父傳值

// child
this.$emit('add', good)
// parent
<Cart @add="cartAdd($event)"></Cart>

事件匯流排

任意兩個元件之間傳值常用事件匯流排 或 vuex的方式。

// Bus:事件派發、監聽和回撥管理
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')