Vue组件封装(以封装一个button组件为例)

r囧r小猫 2023-06-28 06:10 86阅读 0赞

1/在components文件内创建一个button文件,文件内创建一个index.vue文件,在index.vue文件内写的是原型(包含组件的名字,应用的最底层的HTML标签,分别根据什么条件显示什么功能),同时该文件导出的数据为一个对象。

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

2/在button文件下建立一个index.js文件,文件内对新构建组件的名字进行注册。

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

3/ 与button文件同级建立一个index.js文件,对组件进行注册,同时也注册进install中,在导出时,不仅要引出全局的,而且单个的也要引出,便于局部或全局引用。

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

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

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

5/到这里,组件便是封装完成了,在App.vue中可以进行使用了。

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

6/ 运行结果为

format_png

发表评论

表情:
评论列表 (有 0 条评论,86人围观)

还没有评论,来说两句吧...

相关阅读

    相关 封装vue的过程

    vue组件的定义 ● 组件(Component)是Vue.js最强大的功能之一 ● 组件可以扩展HTML元素,封装可重用代码 ● 在较高层面上,组件是自定义元素,Vue.