一 、构建一个vue项目
vue create hello-world
1.建立组件
在src/components/JudyButton.vue
组件内容:javascript
<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
目的是:为了将全部的组件集中,放在一个文件家里便于管理。css
index.js内容vue
// 引入相关的组件 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
完成以后咱们就能够在项目中安装使用了java
三. 在组建中引用和下载
1. 下载
npm i judybutton
2. 引用
在main.js中引用vue-cli
//全局引用 import JudyButton from 'judybutton' import 'judybutton/lib/Judy-Button.css' Vue.use(JudyButton)
在组件中使用 局部引用npm
<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 字段。json