vue自定义插件库及NPM集成实例

一.如何封装vue插件

1.为什么要自定义编写插件

相信做过vue开发的人员,肯定有应用别人的插件在自己的项目中,使用中你会发现没有完全100%符合自己项目场景的插件,可能一个小功能你引入了一堆无用的代码无法减容,同时永远使用别人的插件你就是API工程师,无法进步。

2.插件和组件的差别

插件就是对一系列组件的封装 例如vuex,vue-router;组件是完成某种功能而定制化开发的代码片段,它暴露数据给外部插件。

插件优点:npm上传,开箱即用;多个组件使其丰富;打包带走私有财富;

插件分类:install,vue实例,mixin,directive

3.构建环境

vue-cli4

npm install -g @vue/cli

创建工程

vue create vue-plugins-cc

给据实际情况选择初始化选项(直接默认)

初始化成功后如下建立目录

在这里插入图片描述

4.插件编码

需求:完成msg弹框信息和一组button自定义颜色按钮

1.msg组件

msg/msg.vue

<template>
  <div>
      <div class="msg" ref="msg" :class="{active: msgStatus}">
          <div class="msg-warpper">
              {{text}}
          </div>

      </div>
    
  </div>
</template>

<script>
export default {
  name: 'vue-msg',
  data(){
      return{
          msgStatus: false,
          text: ""
      }
  },
  methods:{
      msgPlugin(msg){
          this.text = msg;
          this.msgStatus = true;
          setTimeout(() => {
              this.msgStatus = false;
          }, 2000);
      }
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.msg{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-120%);
    width: 0;
    min-height: 0;
    text-align: center;
    background-color: rgba(0,0,0,0.6);
    border-radius: 5px;
    color: #ffffff;
    transition: all 0.5s;
    z-index: -1;
    opacity: 0;
}
.msg.active{
    width: 150px;
    min-height: 25px;
    opacity: 1;
    z-index: 10;
}
</style>

2.自定义button按钮组件

button/button.vue

<template>
  <div>
     <button :class="
        type === 'warn' ? 'warn' :
        type === 'error' ? 'error' : 'defaultBtn'">
        <slot></slot>
     </button>
  </div>
</template>

<script>
export default {
  name: 'vue-button',
  props:{
       type:{
            type: String,
            default:"defaultBtn"
        }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.button{
    color: #ffffff;
    border: none;
}
.button.default-btn{
    background-color: blue;
}
.button.warn{
    background-color: orange;
}
.button.error{
    background-color: red;
}
</style>

3.注册组件

pluigins/index.js

单个组件注册的低级做法

import msg from "./msg/msg.vue";
let plugins = {};

plugins.install = function(Vue){
    Vue.prototype.$myMsg = "这是全局属性";
    Vue.prototype.$myMethods = function(){
        console.log("全局方法打印的消息")
    }
    //自定义指令
    Vue.directive('focus',{
        bind: function(){

        },
        //插入节点时
        inserted: function(el){
            el.focus();
        }
    })

    //混入的方式 Vue。mixin({})

    Vue.component(msg.name,msg);
}

export default plugins

高级做法,循环自动注册

const requireComponent = require.context('./', true, /\.vue$/);

const install = Vue =>{
    if(install.installed){
        return
    }
    install.installed = true;

    requireComponent.keys().forEach(fileName => {
        //获取第i各组件的内容
        let config = requireComponent(fileName);
        //获取该组件的名称
        let componentName = config.default.name;
        //注册组件
        Vue.component(componentName, config.default || config);
    });
}

//程序健壮性处理

if(typeof window !== "undefined" && window.Vue){
    install(Vue)
}

export default {install}

5.插件使用

1.在main文件中引入

import Vue from 'vue'
import App from './App.vue'

import vueMsg from './plugins/index.js'

Vue.config.productionTip = false;

//注册插件
Vue.use(vueMsg);

new Vue({
  render: h => h(App),
}).$mount('#app')

2.Hollywood文件中使用

/* eslint-disable no-debugger */
<template>
  <div class="hello">
    <h1>大家好,我是cc</h1>
    <input v-focus placeholder="请输入您的姓名" type="text" v-model="value">
    <button @click="submit">提交</button>
    <vue-msg ref="msg"></vue-msg>
    <vue-button type="warn">警告</vue-button>
    <vue-button type="error">错误</vue-button>
    <vue-button type="warn">默认</vue-button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data(){
      return{
          value:null
      }
  },
  
  methods:{
      submit(){
          if(!this.value){
              console.log(this.$myMsg);
              this.$myMethods();
              this.$nextTick(()=>{
                  this.$refs.msg.msgPlugin("请输入名字")
              })
          }
      }
  },




}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

6.效果

在这里插入图片描述

二. 上传npm

已经写好的插件我们为了使其更好地被广泛应用可以发布到npm公共服务器以供全世界同行使用,当然大多数情况下考虑到知识产权及安全控制也可以公司内部自己搭建npm私有化服务器 目前最好的方案是使用 verdaccio 工具搭建。

本片博文我们演示公网npm方式

1.注册npm账户

具体参见 npm官网

2.修改package文件中的配置

最主要配置是三项
“name”: “vue-msg-plugin-cc”,//名称不要和官网重复
“version”: “0.1.0”,//每次发布版本号要增加
“private”: false,//上官网必须不能设为私有
“license”: “MIT”,//要加上授权协议
“main”: “lib/vue-msg-plugin-cc.umd.min.js”,//入口文件指定

命令: “lib”: "vue-cli-service build --target lib --name vue-msg-plugin-cc --dest lib

{
  "name": "vue-msg-plugin-cc",
  "version": "0.1.0",
  "private": false,
  "license": "MIT",
  "main": "lib/vue-msg-plugin-cc.umd.min.js",
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "lib": "vue-cli-service build --target lib --name vue-msg-plugin-cc --dest lib src/plugins/index.js"
  },
  "dependencies": {
    "core-js": "^3.6.4",
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.2.0",
    "@vue/cli-plugin-eslint": "~4.2.0",
    "@vue/cli-service": "~4.2.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.1.2",
    "vue-template-compiler": "^2.6.11"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}

注意尽量在新建项目中进行打包发布,以防止将开发的工作环境搞坏!!!

3.打包

命令:npm run lib

打包完成项目目录结构:

在这里插入图片描述

4.发布

命令 :npm publish

在这里插入图片描述

5.官网检查

在这里插入图片描述

三.如何在项目中使用已经上传的插件

命令:

npm i vue-msg-plugin-cc

main文件中挂载

import vueMsg from ‘vue-msg-plugin-cc’

Vue.use(vueMsg)

注意:引入css文件路径

在这里插入图片描述

这样就ok!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章