組件系統是 Vue 的一個重要概念,因為它是一種抽象,允許我們使用小型、獨立和通常可復用的組件構建大型應用。幾乎任意類型的應用界面都可以抽象為一個組件樹。組件化能提高開發效率,方便重復使用,簡化調試步驟,提升項目可維護性,便於多人協同開發。
組件通信
props
父給子傳值
// 父組件
<HelloWorld msg="Welcome to Your Vue.js App"/>
// 子組件
props: { msg: String }
自定義事件
子給父傳值
// 父組件
<Cart @onAdd="cartAdd($event)"></Cart>
// 子組件
this.$emit('onAdd', data)
事件總線
任意兩個組件之間傳值,Vue
中已經實現相應接口,下面是實現原理,其實也是典型的發布-訂閱模式。
// 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()
// 組件1
this.$bus.$on('add', handle)
// 組件2
this.$bus.$emit('add')
vuex
任意兩個組件之間傳值,創建唯一的全局數據管理者store,通過它管理數據並通知組件狀態變更。vuex官網
$parent/$roots
兄弟組件之間通信可通過共同祖輩搭橋, $parent
或 $root
。
// 兄弟組件1
this.$parent.$on('foo', handle)
// 兄弟組件2
this.$parent.$emit('foo')
$children
父組件可以通過 $children
訪問子組件實現父子通信。
// 父組件
this.$children[0].xx = 'xxx'
需要注意
$children
並不保證順序,也不是響應式的。
$attrs/$listenners
$attrs
包含了父作用域中不作為 prop 被識別 (且獲取) 的 attribute 綁定 (class
和 style
除外)。
// 父組件
<HelloWorld foo="foo"/>
// 子組件:並未在props中聲明foo
<p>{{ $attrs.foo }}</p>
$listenners
包含了父作用域中的 (不含 .native
修飾器的) v-on
事件監聽器。
// 父組件
<HelloWorld v-on:event-one="methodOne" />
// 子組件
created() {
console.log(this.$listeners) // { 'event-one': f() }
}
$refs
一個對象,持有注冊過 ref
attribute 的所有 DOM 元素和組件實例。
<HelloWorld ref="hw" />
mounted() {
this.$refs.hw.xx = 'xxx'
}
provide/inject
以允許一個祖先組件向其所有子孫后代注入一個依賴。
// 祖先組件提供
provide () {
return { foo: 'bar' }
}
// 后代組件注入
inject: ['foo']
created () {
console.log(this.foo) // => "bar"
}
插槽
插槽語法是Vue 實現的內容分發 API,用於復合組件開發。該技術在通用組件庫開發中有大量應用。
匿名插槽
// comp
<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>
</Comp3>
實現alert插件
在Vue中我們可以使用 Vue.component(tagName, options)
進行全局注冊,也可以是在組件內部使用 components
選項進行局部組件的注冊。
全局組件是掛載在
Vue.options.components
下,而局部組件是掛載在vm.$options.components
下,這也是全局注冊的組件能被任意使用的原因。
有一些全局組件,類似於Message
、Toast
、 Loading
、 Notification
、Alert
通過原型的方式掛載在 Vue
的全局上面。
下面來實現一個簡單Alert
組件,主要是對思路的一個理解,先上效果圖
@/components/alert/src/Alert.vue
<template>
<transition name="fade">
<div class="alert-box-wrapper" v-show="show">
<div class="alert-box">
<div class="alert-box-header">
<div class="alert-box-title">{{ title }}</div>
<div class="alert-box-headerbtn" @click="handleAction('close')">X</div>
</div>
<div class="alert-box-content">
<div class="alert-box-container">{{ message }}</div>
</div>
<div class="alert-box-btns">
<button class="cancel-btn" @click="handleAction('cancel')">{{ cancelText }}</button>
<button class="confirm-btn" @click="handleAction('confirm')">{{ confirmText }}</button>
</div>
</div>
</div>
</transition>
</template>
<script>
export default {
name: 'Alert',
data () {
return {
title: '標題',
message: '這是一段提示內容',
show: false,
callback: null,
cancelText: '取消',
confirmText: '確定'
}
},
methods: {
handleAction (action) {
this.callback(action)
this.destroyVm()
},
destroyVm () { // 銷毀
this.show = false
setTimeout(() => {
this.$destroy(true)
this.$el && this.$el.parentNode.removeChild(this.$el)
}, 500)
}
}
}
</script>
<style lang="less" scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity .3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.alert-box-wrapper {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: center;
align-items: center;
background: rgba(0, 0, 0, 0.5);
.alert-box {
display: inline-block;
width: 420px;
padding-bottom: 10px;
background-color: #fff;
border-radius: 4px;
border: 1px solid #303133;
font-size: 16px;
text-align: left;
overflow: hidden;
.alert-box-header {
position: relative;
padding: 15px;
padding-bottom: 10px;
.alert-box-title {
color: #303133;
}
.alert-box-headerbtn {
position: absolute;
top: 15px;
right: 15px;
cursor: pointer;
color: #909399;
}
}
.alert-box-content {
padding: 10px 15px;
color: #606266;
font-size: 14px;
}
.alert-box-btns {
padding: 5px 15px 0;
text-align: right;
.cancel-btn {
padding: 5px 15px;
background: #fff;
border: 1px solid #dcdfe6;
border-radius: 4px;
outline: none;
cursor: pointer;
}
.confirm-btn {
margin-left: 6px;
padding: 5px 15px;
color: #fff;
background-color: #409eff;
border: 1px solid #409eff;
border-radius: 4px;
outline: none;
cursor: pointer;
}
}
}
}
</style>
@/components/alert/index.js
import Alert from './src/Alert'
export default {
install (Vue) {
// 創建構造類
const AlertConstructor = Vue.extend(Alert)
const showNextAlert = function (args) {
// 實例化組件
const instance = new AlertConstructor({
el: document.createElement('div')
})
// 設置回調函數
instance.callback = function (action) {
if (action === 'confirm') {
args.resolve(action)
} else if (action === 'cancel' || action === 'close') {
args.reject(action)
}
}
// 處理參數
for (const prop in args.options) {
instance[prop] = args.options[prop]
}
// 插入Body
document.body.appendChild(instance.$el)
Vue.nextTick(() => {
instance.show = true
})
}
const alertFun = function (options) {
if (typeof options === 'string' || options === 'number') {
options = {
message: options
}
if (typeof arguments[1] === 'string') {
options.title = arguments[1]
}
}
return new Promise((resolve, reject) => {
showNextAlert({
options,
resolve: resolve,
reject: reject
})
})
}
Vue.prototype.$alert = alertFun
}
}
@/main.js
import Alert from '@/components/alert'
Vue.use(Alert)
使用
this.$alert({
message: '描述描述描述',
title: '提示',
cancelText: '不',
confirmText: '好的'
}).then(action => {
console.log(`點擊了${action}`)
}).catch(action => {
console.log(`點擊了${action}`)
})
// 或
this.$alert('描述描述描述', '提示').then(action => {
console.log(`點擊了${action}`)
}).catch(action => {
console.log(`點擊了${action}`)
})
組件化思考
想象一下,你在工作中接手一個項目,打開一個3000行的vue文件,再打開一個又是4000行,你燥不燥?一口老血差點噴上屏幕。
如何設計一個好的組件?
這個問題我覺得不太容易回答,每個人都有每個人的看法,題中的“組件”可能不僅限於Vue組件,廣義上看,前端代碼模塊,獨立類庫甚至函數在編寫時都應該遵循良好的規則。首先,我們看看組件的出現解決了什么問題,有哪些優點:
- 更好的復用
- 可維護性
- 擴展性
從這三個點出發,各個角度去看一看。
高內聚,低耦合
編程界的六字真言啊。不管什么編程語言,不管前端還是后端,無論是多具體的設計原則,本質上都是對這個原則的實踐。
開發中,不管是 React
還是 Vue
,我們習慣把組件划分為業務組件和通用組件,而達到解耦,提高復用性行。在編寫組件甚至是函數時,應該把相同的功能的部分放在一起(如:Vue3組合式API),把不相干的部分盡可能撇開。試想一下,你想修改某個組件下的一個功能,結果發現牽連了一堆其他模塊,或者你想復用一個組件時,結果引入了其他無關的一堆組件。你是不是血壓一下就到200了?
SOLID 原則
SOLID 是面向對象設計5大重要原則的首字母縮寫,當我們設計類和模塊時,遵守 SOLID 原則可以讓軟件更加健壯和穩定。我覺得它同樣適用於組件的設計。
- 單一職責原則(SRP)
- 開放封閉原則(OCP)
- 里氏替換原則(LSP)
- 接口隔離原則(ISP)
- 依賴倒置原則(DIP)
組件設計參考點
- 無副作用:和純函數類似,設計的一個組件不應該對父組件產生副作用,從而達到引用透明(引用多次不影響結果)。
- 容錯處理/默認值:極端情況要考慮,不能少傳一個或者錯傳一個參數就炸了。
- 顆粒化合適,適度抽象:這個是一個經驗的問題,合理對組件拆分,單一職責原則。
- 可配置/可擴展:實現多場景應用,提高復用性。內部實現太差,API太爛也不行。
- 詳細文檔或注釋/易讀性:代碼不僅僅是給計算機執行的,也是要給人看的。方便你我他。你懂的!
- 規范化:變量、方法、文件名命名規范,通俗易懂,最好做到代碼即注釋。你一會大駝峰(UserInfo)、一會小駝峰(userInfo)、一會烤串(user-info),你信不信我捶死你。
- 兼容性:同一個系統中可能存在不同版本Vue編寫的組件,換個小版本就涼涼?
- 利用框架特性:Vue框架本身有一些特性,如果利用的好,可以幫我們寫出效率更高的代碼。比如
slot
插槽、mixins
;真香!