封装组件发布到npm上,项目中可以npm install,这里做一个简单的封装例子(第二步)


第一步就是我们平常的写的vue组件,比如dialog,我的目录如下,这里面目录自己随意写

 main.vue组件,编写组件

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

2.设置弹窗消失的时间




 

第二步注册 dialog组件

1.利用 Vue.extend 构造器把dialog组件挂载到 vue 实例下

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

let DialogConstructor = Vue.extend(Main)

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

第三步发布组件

1. 在 src 下新建 index.js 文件,引入需要上传的组件,这里主要用到 vue 两种注册组件和插件的方法

1.Vue.component(key, val)

2.Vue.use()

 index.js

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 // 通过插件单独引入

到这里我们组件封装,准备要发布到npm的工作做完,下面就是推送到npm上