vue封装插件并发布到npm

@【vue自定义插件&上传npm】

写插件

在项目根目录新建glugins文件夹,目录如下

  • glugins
    • lib
      • index.js
    • index.js
  • glugins>lib>index.js

const Plugins = {
    //Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象
    install(Vue,option){
        // 添加全局方法或 property
        Vue.myGlobalMethod = function () {
            // 逻辑...
        }
        //添加全局资源
        Vue.directive('rotate',{
            bind:function(){
            //只调用一次,指令第一次绑定到元素时调用
            //我这里让元素旋转并改变字体颜色
            let [el,...other] = arguments
            el.onmousemove = function(){
                el.style.color = 'pink'
                el.style.display = 'inline-block'
                el.style.transition = 'all 1s'
                el.style.transform = 'rotateZ(360deg)'
            }
            el.onmouseleave = function(){
                console.log("onmouseleave")
                el.style.color = '#000'
                el.style.transform = 'rotateZ(0deg)'
            }
            },
            inserted: function () {
            //被绑定元素插入父节点时调用
            },
            update: function () {
            //所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。
            //但是你可以通过比较更新前后的值来忽略不必要的模板更新 。
            },
            componentUpdated: function () {
            //指令所在组件的 VNode 及其子 VNode 全部更新后调用。
            },
            unbind: function () {
            //只调用一次,指令与元素解绑时调用。
            }
        
        })

        // 注入组件选项
        Vue.mixin({
            created: function () {
            // 逻辑...
            }
        })

        //  添加实例方法
        Vue.prototype.$myMethod = function (methodOptions) {
            // 逻辑...
        }
    }
}
export default Plugins
  • glugins> index.js
//module.exports 提供了暴露接口的方法
module.exports = require('./lib')

在main.js 引入

import rotate from '../plugins/index.js'
Vue.use(rotate);

页面使用

<template>
  <div>
  	 <img  v-rotate src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3036316726,676055399&fm=26&gp=0.jpg" alt="">
  </div>
</template>

发布到npm

首先你的有一个npm账号,前往注册

打开glugins所在目录cmd窗口

执行命令:npm init -y 。 初始化插件,生成配置文件package.json 。

{
  "name": "@haoyan/plugintext",  //名字,注意文件的name不要重名
  "version": "1.0.0",  //版本
  "description": "",   //描述
  "main": "index.js",
  "directories": {
    "lib": "lib"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],  //关键词
  "author": "",    //作者
  "license": "ISC"
}

接下来是登录发布

命令:npm login
然后依次输入用户名 密码 email
命令:npm publish

使用: npm下载,main.js 引入,页面使用。

//上传npm的在定义插件
import rotate from 'lihao2'
Vue.use(rotate);
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值