zoukankan      html  css  js  c++  java
  • Vue组件封装(以封装一个button组件为例)

    8月收获

    摘录自https://www.cnblogs.com/muzishijie/p/11291295.html

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

    <template>

        <div :class="type == 'default'?'btn default':type == 'primary'?'btn primary':type == 'danger'?'btn danger':'btn default'">
            <slot></slot>
        </div>
    </template>

    <script>
    export default {
        name:"alley-Button",
        props:{
            type:{
                type:String,
                default:"Default"
            }
        }
    }
    </script>


    <style>
        .btn{
              100px;
             height: 40px;
             text-align: center;
             line-height:40px;
        }
        .default{

            border: 1px solid green;

        }

         .primary{

            border: 1px solid #ccc;
        }

         .danger{

               border: 1px solid red;
        }
    </style>

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

    import Button from "./index.vue";
    
     Button.install = (Vue)=>{
        Vue.component(Button.name,Button)
    }
    
    export default Button;

     三:与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
     }

     四:要在main.js中进行引用

    import AlleyUI from "./components"
    Vue.use(AlleyUI);


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

    <template>
      <div>
        <alley-Button type="default" style="margin:10px">按钮</alley-Button>
        <alley-Button type="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>

    小结:so simple

  • 相关阅读:
    省选知识点
    寒假练习
    水题欢乐赛-套路
    2019年12月(2)
    洛谷P1347 排序
    Aizu
    2019年12月(1)
    【CSP2019】
    联系博主
    UVA1420 Priest John's Busiest Day【贪心】
  • 原文地址:https://www.cnblogs.com/DZzzz/p/13479465.html
Copyright © 2011-2022 走看看