Vue組件封裝(以封裝一個button組件為例)


1/在components文件內創建一個button文件,文件內創建一個index.vue文件,在index.vue文件內寫的是原型(包含組件的名字,應用的最底層的HTML標簽,分別根據什么條件顯示什么功能),同時該文件導出的數據為一個對象。

 1 <template>
 2     <div :class="type == 'Default'?'btn default':type == 'primary'?'btn primary':type == 'danger'?'btn danger':'btn default'">
 3         <slot></slot>
 4     </div>
 5 </template>
 6 
 7 <script>
 8 export default {
 9     name:"alley-Button",
10     props:{
11         type:{
12             type:String,
13             default:"Default"
14         }
15     }
16 }
17 </script>
18 
19 
20 <style>
21     .btn{
22          width: 100px;
23          height: 40px;
24          color:#fff;
25          text-align: center;
26          line-height:40px;
27     }
28     .default{
29        
30         background: red;
31        
32     }
33 
34      .primary{
35       
36         background: yellow;
37     }
38 
39      .danger{
40      
41         background: #ccc;
42     }
43 </style>

2/在button文件下建立一個index.js文件,文件內對新構建組件的名字進行注冊。

1 import Button from "./index.vue";
2 
3  Button.install = (Vue)=>{
4     Vue.component(Button.name,Button)
5 }
6 
7 export default Button;

3/ 與button文件同級建立一個index.js文件,對組件進行注冊,同時也注冊進install中,在導出時,不僅要引出全局的,而且單個的也要引出,便於局部或全局引用。

 
 1 import Button from "./button"
 2  3  4  const components = [
 5      Button
 6  ]
 7  8  9  //vue。use使用時,必須要有install方法。參數就是vue。
10  const install  = (Vue)=>{
11      for(var key in components){
12          Vue.component(components[key].name,components[key])
13      }
14  }
15 16 17  export default {
18      install,
19      Button
20  }

4/要在main.js中進行引用

1  import Vue from 'vue'
2  import App from './App.vue'
3  import AlleyUI from "./components"
4  Vue.config.productionTip = false
5  Vue.use(AlleyUI);
6 7  new Vue({
8    render: h => h(App),
9  }).$mount('#app')

5/到這里,組件便是封裝完成了,在App.vue中可以進行使用了。

 
 1 <template>
 2    <div id="app">
 3      <alley-Button>按鈕</alley-Button>
 4      <alley-Button type="primary">按鈕</alley-Button>
 5      <alley-Button>按鈕</alley-Button>
 6      <alley-Button>按鈕</alley-Button>
 7    </div>
 8  </template>
 9 10  <script>
11 12  export default {
13    name: 'app',
14   
15  }
16  </script>
17 18  <style>
19 20  </style>

6/ 運行結果為

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM