封装Vue组件并发布到npm上
<template>
<div>
<button :class="type == "Default"?"btn default":type == "primary"?"btn primary":type == "danger"?"btn danger":"btn default""
@click="confirm"
>
<slot></slot>
</button>
</div>
</template>
<script>
export default {
name:"judy-button",
props:{
type:{
type:String,
default:"Default"
}
},
methods:{
confirm(){
this.$emit("confirm")
}
}
}
</script>
<style scoped>
.btn{
width: 100px;
height: 40px;
color:#fff;
text-align: center;
line-height:40px;
border: none;
cursor: pointer;
}
.default{
background-color:rgb(26, 185, 87);
box-shadow:0 7px 0 rgb(28, 158, 78), 0 8px 3px rgba(0, 0, 0, 0.3);
}
.primary{
background: rgba(18, 117, 197);
box-shadow: 0 7px 0 rgba(7, 48, 66, 0.829),0 8px 3px rgba(0, 0, 0, 0.3);
}
.danger{
background: rgb(255, 20, 20);
}
.default:hover,.default:focus{
background-color:rgba(26, 185, 87,0.6);
}
.primary:hover,.primary:focus{
background: rgba(18, 117, 197, 0.75);
}
</style>
2. App.vue同级创建index.js
目的是:为了将所有的组件集中,放在一个文件家里便于管理。
index.js内容
// 引入相关的组件
import JudyButton from "./components/JudyButton.vue"
const components = [
JudyButton,
//还可以再写别的组件
]
var comObj = {};
comObj.install = (Vue) => {
components.map(component => {
Vue.component(components[key].name, components[key]) //注册组件
comObj[components[key].name] = components[key];
})
}
/* 支持使用标签的方式引入 */
if (typeof window !== "undefined" && window.Vue) {
install(window.Vue);
}
export default comObj //默认全局导出
export {
JudyButton // 按需导出
}
3. 修改package.json里面的值
{
"name": "judybutton",
"version": "0.0.1",
"private": false,
"main": "lib/Judy-Button.umd.min.js",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"build:components": "vue-cli-service build --dest lib --target lib src/index.js",
"lint": "vue-cli-service lint"
},
二. 发布到npm
npm login //登录npm
npm publish
完成之后我们就可以在项目中安装使用了
三. 在组建中引用和下载
1. 下载
npm i judybutton
2. 引用
在main.js中引用
//全局引用
import JudyButton from "judybutton"
import "judybutton/lib/Judy-Button.css"
Vue.use(JudyButton)
在组件中使用 局部引用
<template>
<div>
<judy-button
type="primary"
@confirm="confirm"
>按钮</judy-button>
</div>
</template>
<script>
//局部引用 => 按需引用
import { JudyButton } from "judybutton"
import "judybutton/lib/Judy-Button.css"
export default {
name:"show-blog",
components:{
JudyButton
},
data(){
return {
}
},
mounted(){
},
methods:{
confirm(){
console.log("点击按钮")
}
}
}
</script>
注意:每次上到 npm 上需要更改版本号,package.json 里的 version 字段。