最近想要做一些vue的插件练一下手,于是现在需要解决的问题有两个。一个是怎么写vue的插件,一个是写完后怎么上传npm。
一、如何写一个vue插件
首先在进行插件创作的时候,先建立一个普通的vue项目进行编写。
vue create vue-button-z
然后创建plugins文件夹,和plugins下的lib文件夹,在lib文件夹下写你的插件代码
1.插件代码编写
这是button.vue 文件示例,就像写普通vue组件一样,根据你的需求写
// button.vue
<template>
<button :style="style">
<slot>button</slot>
</button>
</template>
<script>
export default {
name: 'ta-button', //你的组件名称,使用此名称全局挂载
props: {
type: {
type: String,
default: 'primary',
},
size: {
type: String,
default: 'default',
},
},
setup(props) {
const Colors = {
primary: '#477bec',
warning: '#ffc400',
danger: '#ff7300',
info: '#cfcfcf',
}
const Sizes = {
small: '2px 10px',
default: '6px 14px',
large: '8px 20px',
}
console.log('size:', props.size, 'type:', props.type)
const style = {
backgroundColor: Colors[props.type],
padding: Sizes[props.size],
color: '#fff',
fontSize: '14px',
borderRadius: '4px',
}
return { style }
},
}
</script>
<style scoped>
button {
border: none;
outline: none;
}
</style>
2.plugins/index.js文件的编写
插件的代码写完后,对index.js进行编写
import TaButton from './button/button.vue'
export default {
install: (app) => {
//挂载全局变量或方法
app.config.globalProperties.$hello = 'hello! Think for using my plugin'
//全局挂载组件
app.component(TaButton.name, TaButton)
//使用依赖注入
app.privide('age','18')
//自定义指令
//app.directive('my-directive', {
// mounted (el, binding, vnode, oldVnode) {
// some logic ...
// }
//})
}
}
到此为止,关于插件编写的部分就结束了,还差一步就能发布了,那就是测试。
3.简单测试代码
在main.js
文件中引入自己的插件
import { createApp } from "vue";
import App from "./App.vue";
import MyPlugin from './plugins'
//MyPlugin 就是我们编写的插件
createApp(App).use(MyPlugin).mount("#app");
尝试使用
<template>
<ta-button type="danger" size="small"> small </ta-button>
<ta-button type="primary"> default </ta-button>
<ta-button type="warning" size="large"> large </ta-button>
</template>
成功运行
我们已经可以准备发布自己精心编写的程序到npm上供别人使用了。
二、发布npm
另起一个空白的文件夹,只放如下文件
然后编写README.md
文件,这个就不示例了。
重要的是编写package.json
文件,示例如下
{
"name": "vue-button-tang", //你的包的名称
"version": "0.0.1", //版本
"description": "vue plugins", //详细的描述
"main": "index.js", //入口文件
"directories": { //源码地址
"lib":"lib"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"vue3"
],
"author": "tinytang", //作者
"license": "ISC"
}
很好,本地的工作已经做好的,现在你需要一个npm账号,进入下面的网址注册一个https://www.npmjs.com/
注册之后记得进行邮箱验证,不然会报403
错误
然后将npm的源换回npmjs,一般来说我们都会设置为淘宝的源,如果不换回来可能会报错。
npm install -g nrm
nrm use npm
一切准备就绪,只差一个命令
npm publish
这样你的插件的上传成功了。可以尝试在npm网站上搜索,也可以尝试自己安装一下自己的包,看看能不能用。