文章目錄
一.如何封裝vue插件
1.爲什麼要自定義編寫插件
相信做過vue開發的人員,肯定有應用別人的插件在自己的項目中,使用中你會發現沒有完全100%符合自己項目場景的插件,可能一個小功能你引入了一堆無用的代碼無法減容,同時永遠使用別人的插件你就是API工程師,無法進步。
2.插件和組件的差別
插件就是對一系列組件的封裝 例如vuex,vue-router;組件是完成某種功能而定製化開發的代碼片段,它暴露數據給外部插件。
插件優點:npm上傳,開箱即用;多個組件使其豐富;打包帶走私有財富;
插件分類:install,vue實例,mixin,directive
3.構建環境
vue-cli4
npm install -g @vue/cli
創建工程
vue create vue-plugins-cc
給據實際情況選擇初始化選項(直接默認)
初始化成功後如下建立目錄
4.插件編碼
需求:完成msg彈框信息和一組button自定義顏色按鈕
1.msg組件
msg/msg.vue
<template>
<div>
<div class="msg" ref="msg" :class="{active: msgStatus}">
<div class="msg-warpper">
{{text}}
</div>
</div>
</div>
</template>
<script>
export default {
name: 'vue-msg',
data(){
return{
msgStatus: false,
text: ""
}
},
methods:{
msgPlugin(msg){
this.text = msg;
this.msgStatus = true;
setTimeout(() => {
this.msgStatus = false;
}, 2000);
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.msg{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-120%);
width: 0;
min-height: 0;
text-align: center;
background-color: rgba(0,0,0,0.6);
border-radius: 5px;
color: #ffffff;
transition: all 0.5s;
z-index: -1;
opacity: 0;
}
.msg.active{
width: 150px;
min-height: 25px;
opacity: 1;
z-index: 10;
}
</style>
2.自定義button按鈕組件
button/button.vue
<template>
<div>
<button :class="
type === 'warn' ? 'warn' :
type === 'error' ? 'error' : 'defaultBtn'">
<slot></slot>
</button>
</div>
</template>
<script>
export default {
name: 'vue-button',
props:{
type:{
type: String,
default:"defaultBtn"
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.button{
color: #ffffff;
border: none;
}
.button.default-btn{
background-color: blue;
}
.button.warn{
background-color: orange;
}
.button.error{
background-color: red;
}
</style>
3.註冊組件
pluigins/index.js
單個組件註冊的低級做法
import msg from "./msg/msg.vue";
let plugins = {};
plugins.install = function(Vue){
Vue.prototype.$myMsg = "這是全局屬性";
Vue.prototype.$myMethods = function(){
console.log("全局方法打印的消息")
}
//自定義指令
Vue.directive('focus',{
bind: function(){
},
//插入節點時
inserted: function(el){
el.focus();
}
})
//混入的方式 Vue。mixin({})
Vue.component(msg.name,msg);
}
export default plugins
高級做法,循環自動註冊
const requireComponent = require.context('./', true, /\.vue$/);
const install = Vue =>{
if(install.installed){
return
}
install.installed = true;
requireComponent.keys().forEach(fileName => {
//獲取第i各組件的內容
let config = requireComponent(fileName);
//獲取該組件的名稱
let componentName = config.default.name;
//註冊組件
Vue.component(componentName, config.default || config);
});
}
//程序健壯性處理
if(typeof window !== "undefined" && window.Vue){
install(Vue)
}
export default {install}
5.插件使用
1.在main文件中引入
import Vue from 'vue'
import App from './App.vue'
import vueMsg from './plugins/index.js'
Vue.config.productionTip = false;
//註冊插件
Vue.use(vueMsg);
new Vue({
render: h => h(App),
}).$mount('#app')
2.Hollywood文件中使用
/* eslint-disable no-debugger */
<template>
<div class="hello">
<h1>大家好,我是cc</h1>
<input v-focus placeholder="請輸入您的姓名" type="text" v-model="value">
<button @click="submit">提交</button>
<vue-msg ref="msg"></vue-msg>
<vue-button type="warn">警告</vue-button>
<vue-button type="error">錯誤</vue-button>
<vue-button type="warn">默認</vue-button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data(){
return{
value:null
}
},
methods:{
submit(){
if(!this.value){
console.log(this.$myMsg);
this.$myMethods();
this.$nextTick(()=>{
this.$refs.msg.msgPlugin("請輸入名字")
})
}
}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
6.效果
二. 上傳npm
已經寫好的插件我們爲了使其更好地被廣泛應用可以發佈到npm公共服務器以供全世界同行使用,當然大多數情況下考慮到知識產權及安全控制也可以公司內部自己搭建npm私有化服務器 目前最好的方案是使用 verdaccio 工具搭建。
本片博文我們演示公網npm方式
1.註冊npm賬戶
具體參見 npm官網
2.修改package文件中的配置
最主要配置是三項
“name”: “vue-msg-plugin-cc”,//名稱不要和官網重複
“version”: “0.1.0”,//每次發佈版本號要增加
“private”: false,//上官網必須不能設爲私有
“license”: “MIT”,//要加上授權協議
“main”: “lib/vue-msg-plugin-cc.umd.min.js”,//入口文件指定
命令: “lib”: "vue-cli-service build --target lib --name vue-msg-plugin-cc --dest lib
{
"name": "vue-msg-plugin-cc",
"version": "0.1.0",
"private": false,
"license": "MIT",
"main": "lib/vue-msg-plugin-cc.umd.min.js",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"lib": "vue-cli-service build --target lib --name vue-msg-plugin-cc --dest lib src/plugins/index.js"
},
"dependencies": {
"core-js": "^3.6.4",
"vue": "^2.6.11"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.2.0",
"@vue/cli-plugin-eslint": "~4.2.0",
"@vue/cli-service": "~4.2.0",
"babel-eslint": "^10.0.3",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.1.2",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {
}
},
"browserslist": [
"> 1%",
"last 2 versions"
]
}
注意儘量在新建項目中進行打包發佈,以防止將開發的工作環境搞壞!!!
3.打包
命令:npm run lib
打包完成項目目錄結構:
4.發佈
命令 :npm publish
5.官網檢查
三.如何在項目中使用已經上傳的插件
命令:
npm i vue-msg-plugin-cc
main文件中掛載
import vueMsg from ‘vue-msg-plugin-cc’
Vue.use(vueMsg)
注意:引入css文件路徑
這樣就ok!