封装一个vue component

npm  install  countup

index.vue 如下:

<template>

<span ref='countup'></span>

</template>

 

<script>

import CountUp from 'countup.js'

export default {

name: 'countup-demo',

props: {

start: {

type: Number,

default: 0

},

end: {

type: Number,

default: 2017

},

decimal: {

type: Number,

default: 0

},

duration: {

type: Number,

default: 2.5

},

options: {

type: Object

}

},

data() {

return {

numAnim: null

}

},

mounted() {

this.initCountUp()

},

methods: {

initCountUp() {

// this.numAnim = new CountUp(this.$refs.countup, 0, 2017)

this.numAnim = new CountUp(this.$refs.countup,

this.start,

this.end,

this.decimal,

this.duration,

this.options)

this.numAnim.start();

}

}

}

</script>

使用组件

<vue-count-up :end="2500" :duration="2.5"></vue-count-up>

上传 npm

在不跨项目的情况下之前所做的已经满足需求了。但我们不能就此满足,我想让世界上更多的人来使用我的插件,这时候就要上传 npm

首先我们新建一个index.js

import CountTo from './vue-countTo.vue'

// 导出模块
export default CountTo

//global 情况下 自动安装
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.component('count-to', CountTo)
}

同时我们也要改造一下 webpack 的配置,因为不是所有使用你组件的人都是通过 npm 安装使用 import 引入组件的的。

还有很多人是通过 <script> 标签的方式直接引入的,所以我们要将 libraryTarget 改为 umd 格式

library: 'CountTo',
libraryTarget: 'umd',
umdNamedDefine: true

大功告成,现在只要将它发布到 npm 就可以了,首先注册一个npm 账号,
之后配置自己的 package.json (注意填写 version,每次发布的 version 不能相同;main 为入口文件地址)。
之后只要一行命令 npm publish 你的项目就发到 npm 了

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值