关于javascript:Vue之组件化理解

90次阅读

共计 6385 个字符,预计需要花费 16 分钟才能阅读完成。

组件零碎是 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 绑定 (classstyle 除外)。

// 父组件
<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  下,这也是全局注册的组件能被任意应用的起因。

有一些全局组件,相似于MessageToastLoadingNotificationAlert 通过原型的形式挂载在 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;真香!

正文完
 0