Vue之组件化理解__Vue.js
发布于 3 年前 作者 banyungong 1198 次浏览 来自 分享
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利

组件系统是 Vue 的一个重要概念,因为它是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用。几乎任意类型的应用界面都可以抽象为一个组件树。组件化能提高开发效率,方便重复使用,简化调试步骤,提升项目可维护性,便于多人协同开发。

components.png

组件化思考

想象一下,你在工作中接手一个项目,打开一个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 ;真香!

组件通信

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 组件,主要是对思路的一个理解,先上效果图

alert.gif

@/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}`)
})
```<p style="line-height: 20px; color: #ccc">
        版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
        作者: 明么
        原文链接:<a href='https://juejin.im/post/6953439409857363982'>https://juejin.im/post/6953439409857363982</a>
      </p>
回到顶部