在开发项目过程中,通常会用到很多功能和设计相类似的组件,为了避免重复造轮子,我们经常会用到一些第三方组件,比如 vux,vant。但是这样会引入太多没用到的组件,造成打包体积过大。所以我们有必要封装一些基础的组件用于开发。

源码地址

组件封装必要性

  • 提高开发效率,避免重复造轮子
  • 调用同一组件,统一 UI 样式
  • 便于协同开发,提高可维护性
  • 减少对第三方组件的使用,定制个性化的组件

toast 和 dialog 组件封装

toast 和 dialog 组件基本是每一个移动端项目都会用到的,下面我将介绍如何封装这两个组件,并发布到 npm 供下载使用。

1.必备知识储备

  • vue 的基础知识
  • Vue.extend 构造器
  • $mount 手动挂载实例
  • vue 组件的传值传参
  • 理解 Vue 构造函数及 prototype
  • webpack 打包
  • npm 基础知识

最终我们要达到这样的效果,从 npm 下载依赖包,直接调用

this.$toast({ msg: '手机号码不能为空' })

this.$toast({
  msg: '成功提示',
  type: 'success'
})

this.$dialog({
  title: '删除提示',
  text: '是否确定删除此标签?',
  showCancelBtn: true,
  confirmText: '确认',
  confirm(content) {
    alert('删除成功')
  }
})

2.编写组件

根据传入的 type 确定弹窗的类型(成功提示,失败提示,警告,加载,纯文字)
设置弹窗消失的时间

<template>
  <div>
    <transition name="fade">
      <div class="little-tip" v-show="showTip">
        <img src="assets/img/success.png" alt="" width="36" v-if="type=='success'" />
        <img src="assets/img/fail.png" alt="" width="36" v-if="type=='fail'" />
        <img src="assets/img/warning.png" alt="" width="36" v-if="type=='warning'" />
        <img src="assets/img/loading.png" alt="" width="36" v-if="type=='loading'" class="loading" />
        <span>{{msg}}</span>
      </div>
    </transition>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        showTip: true,
        msg: '',
        type: ''
      }
    },
    mounted() {
      setTimeout(() => {
        this.showTip = false
      }, 1500)
    }
  }
</script>
<style lang="less" scoped>
  /* 样式略 */
</style>

3.注册 toast 组件

3.1、利用 Vue.extend 构造器把 toast 组件挂载到 vue 实例下

import Vue from 'vue'
import Main from './main.vue'

let Toast = Vue.extend(Main)

let instance
const toast = function(options) {
  options = options || {}
  instance = new Toast({
    data: options
  })
  instance.vm = instance.$mount()
  document.body.appendChild(instance.vm.$el)
  return instance.vm
}
export default toast

3.2 在 main.js 引入 toast 组价并挂载在 vue 原型上

import Vue from 'vue'
import toast from './components/toast'
Vue.prototype.$toast = toast

至此就可以在项目中直接调用组件了。dialog 组件的封装也是同样的方法。
下面介绍如何把组件发布到 npm 上。

发布 npm 组件

1. 在 src 下新建 index.js 文件,引入需要上传的组件

这里主要用到 vue 两种注册组件和插件的方法
  • Vue.component(key, val)
  • Vueu.use()
import toast from './components/toast'
import dialog from './components/dialog'
const YMUI = {
  // 这里是后续补充的组件
}

const install = function(Vue, opts = {}) {
  if (install.installed) return
  Object.keys(YMUI).forEach(key => {
    Vue.component(key, YMUI[key])
  })

  Vue.prototype.$toast = toast
  Vue.prototype.$dialog = dialog
}

// auto install
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue) // 通过use方式全部引入
}

const API = {
  install,
  ...YMUI
}

export default API // 通过插件单独引入

2.修改 webpack.dist.prod.conf 的打包配置

  • entry: 入口文件配置,打包时入口文件为 index.js
  • filename: 是打包生成文件的名字
  • libraryTarget: 配置 webpack 打包内容的模块方式的参数
module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/index.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: 'vue-mobile-ymui.js',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath
  }
}

3.修改 package.json 的配置

  • name: 组件名字
  • version: 版本号
  • main: 字段,指定了该 npm 包引用的入口(记住一定要记得添加,并且文件名应与上面第二点提到的保持一致)

    {
    "name": "vue-mobile-ymui",
    "version": "1.0.3",
    "description": "a mobile compoment",
    "author": "lzg",
    "private": false,
    "main": "./dist/vue-mobile-ymui.js",
    "scripts": {
      "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
      "start": "npm run dev",
      "lint": "eslint --ext .js,.vue src",
      "build": "node build/build.js",
      "build-js": "webpack --config build/webpack.dist.prod.conf.js"
    },
    }

    4.发布 npm 组件

npm login 注册并登陆 npm 账号
npm publish 发布组件

注意点:

  • 邮箱必须要先注册
  • 包名不能有大写字母/空格/下滑线,不能重复

5.升级 npm 包

1.打包修改后的代码
2.修改包的版本(package.json 里的 version 字段)version 的字段表现为:”version“:"x.y.z"

  • 有很大的改动,无法向后兼容,增加 x
  • 增加了新特性,但仍能向后兼容,增加 y
  • 修复 bug,小改动,增加 z

使用 npm 组件

1.安装依赖

npm install vue-mobile-ymui

2.在 mian.js 引入并 use()

import UI from 'vue-mobile-ymui'
Vue.use(UI)

3.在页面直接调用

this.$toast({
  msg: '成功提示',
  type: 'success'
})

至此,封装vue组件并发布到npm并调用的方法就接受完了。
后续的继续封装其他组件,敬请关注
WeChatf7c0b41388f4ff815da237a2260a83aa.png

最后修改:2021 年 03 月 29 日
如果觉得我的文章对你有用,请随意赞赏