Vue元件封裝(以封裝一個button元件為例)
阿新 • • 發佈:2020-08-11
8月收穫
摘錄自https://www.cnblogs.com/muzishijie/p/11291295.html
1/在components檔案內建立一個button檔案,檔案內建立一個index.vue檔案,在index.vue檔案內寫的是原型(包含元件的名字,應用的最底層的HTML標籤,分別根據什麼條件顯示什麼功能),同時該檔案匯出的資料為一個物件。
<template> <div> <alley-Button type="default" style="margin:10px">按鈕</alley-Button> <alley-Buttontype="primary" style="margin:10px">按鈕</alley-Button> <alley-Button type="danger" style="margin:10px">按鈕</alley-Button> <alley-Button style="margin:10px">按鈕</alley-Button> </div> </template> <style scoped lang="scss"> </style>
2/在button檔案下建立一個index.js檔案,檔案內對新構建元件的名字進行註冊。
import Button from "./index.vue";
Button.install = (Vue)=>{
Vue.component(Button.name,Button)
}
export default Button;
3/ 與button檔案同級建立一個index.js檔案,對元件進行註冊,同時也註冊進install中,在匯出時,不僅要引出全域性的,而且單個的也要引出,便於區域性或全域性引用。
import Button from "./button"; const components = [ Button ]; //vue.use使用時,必須要有install方法,引數就是vue。 const install = (Vue)=>{ for(var key in components){ Vue.component(components[key].name,components[key]) } } export default { install, Button }
4/要在main.js中進行引用