VUE自定义插件库及NPM集成

VUE自定义插件库及NPM集成

一、如何封装VUE插件

1. 插件与组件

组件:对某功能或某模块的封装

插件:对一系列组件的封装

关系:插件可以封装组件,组件暴露数据给插件

2. 插件的优点

  • 开箱即用

  • 功能比组件更强大,更丰富

  • 一次引入,终生受益

  • 打包带走,随走随用

3. 插件分类

install ,vue实例,mixin(vue3.0已不推荐使用),directive
在这里插入图片描述

4. 插件实现

  1. src目录下创建plugins文件夹

  2. plugins文件夹下创建组件文件夹,如msg

  3. msg下创建msg.vue(组件的完整模板)

<template>
  <div class='msg' ref='msg' :class="{active: msgStatus}">
    <div class="msg-warpper">{{text}}</div>
  </div>
</template>
<script>
  export default {
    name: 'vue-msg',
    props: {
      msg: String
    },
    data() {
      return {
        text: '',
        msgStatus: false
      }
    },
    methods: {
      msgPlugin(msg, time=2000) {
        this.text = msg;
        this.msgStatus = true;
        setTimeout(() => {
          this.msgStatus = fasle;
        }, time)
      }
    }
  }
</script>
<style scoped>

</style>
  1. plugins下创建index.js入口文件
import msg from './msg/msg.vue'
let plugin = []
plugin.install = function(Vue) {
  Vue.prototype.$msg = "我是个全局属性"
  Vue.prototype.$myMythod = () => {
    console.log("我是个全局方法")
  }
  // 自定义指令
  Vue.directive('focus'. {
    bind: function() {},
    inserted: function(el) {  // 当el被插入到页面时触发
      el.focus()
    }
  })
  Vue.component(msg.name, msg)
}
export default plugin
const requireComponent = require.context('./', true, /\.vue$/)  //目录,是否匹配子文件夹,文档类型
const install = (Vue) => {
  if (install.installed) return
  install.installed
  requireComponent.keys().forEach(filname => {
    const config = requireComponent(fileName)
    const componentName = config.default.name
    Vue.component(componentName, config.default || config)
  })
  Vue.directive('focus'. {
    bind: function() {},
    inserted: function(el) {
      el.focus()
    }
  })
}
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}
export default {
  install
}
  1. Main.js引入并全局注册
import vueMsg from './plugins/index.js'
Vue.use(vueMsg)
  1. 组件中使用插件库中的插件
<vue-msg ref="msg"></vue-msg>
this.$refs.msg.msgPlugin("test", 2000)

二、集成到npm

  1. 配置packag.json
"name": "vue-plugins-demo",  // 插件名称
"private": false,  // 是否私有,一定改为非私有false
"description": "",  // 插件描述
"license": "MIT",  // 开源协议
"main": 'lib/vue-plugins-demo.umd.min.js'  // 入口文件,打包后lib文件夹下
"script": {
  // target:打包目标路径;name:插件名称;dest:打包入口文件
  "lib": "vue-cli-service build --target lib --name vue-plugins-demo --dest lib src/plugins/index.js"
}
  1. 打包
npm run lib
  1. 发布到npm
npm login  // 登录npm,无账号需先注册
username:  // 输入用户名
password:  // 输入密码
email:  // 输入邮箱

// 登录成功,发布即可
npm publish
  1. 项目中引用
npm i vue-plugins-demo
main.js中引入,注意必须引入css

三、优化与扩展

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值