【Vue】參照elementui編寫自定義的vue組件


轉自:https://www.jianshu.com/p/10b39aacd738

1:先來回顧一下vue組件的局部注冊與全局注冊

       1.1定義組件:

1.2然后在另外一個組件HelloWorld.vue內進行局部注冊:

1.3我們也可以再main.js里進行全局注冊:

2 : 使用Vue.use()

我們在開發過程中遇到大量需要反復使用的組件時都會進行全局注冊,那么如何elementui一樣Vue.use()來注冊組件,請回顧 文檔 對插件的擴展 或者戳 這里

2.1我們建立一個文件夾存放組件,寫一個alert組件

2.2然后在 index.js里配置下這個組件的install

2.3這樣的話就可以在main.js 里面

import zkxAlert from '../componentLib/alert '

Vue.use(zkxAlert)

2.3如何像elementui 一樣 use(elementui) 就可以使用全部組件

在componentLib/index.js 內如上處理

3:使用 prop, 事件, slot 讓組件變得靈活;

<template>
    <!--可以再這個地方添加動畫效果-->
    <transition>
        <div  v-show="visible" class="z-alert" :class="typeClass">
            {{title}}
            <slot></slot>
            <span class="z-alert-close" v-show="closable" @click="close()">關閉</span>
        </div>
    </transition>
</template>

<script>
    export default{
        name:'zkxAlert',
        props:{
            //一個alert 組件 最基本的要有    標題   不同類型的提示   關閉事件
            title:{
                type: String,
                default: '',
                required: true
            },
            //type 會有 success warning error 三種類型
            type: {
                type: String,
                default: 'success'
            },
            //是否可以點擊關閉  默認可以
            closable: {
                type: Boolean,
                default: true
            },
        },
        data() {
          return {
            visible: true
          };
        },
    
        methods: {
          close() {
            this.visible = false;
          }
        },
        computed:{
           //通過調用的type 來計算需要顯示的class 
            typeClass(){
                return `z-alert--${this.type}`;
            }
        }
        
        
    }
</script>

<style scoped="scoped">
    .z-alert{
        width:1000px;
        /*height: 50px;*/
        line-height: 50px;
        margin: auto;
    }
    .z-alert-close{
        float:right;
        line-height: 50px;
    }
    .z-alert--success{
        background: #f0f9eb;
        color:cadetblue;
    }
    .z-alert--warning{
        background: #fdf6ec;
        color:#e6a28b;
    }
    .z-alert--error{
        background: #fef0f0;
        color:#f681b0;
    }
</style>

4.下面我們use組件之后,調用看下

<zkxAlert title="小豬佩奇身上紋" :closable='false'></zkxAlert>
    <zkxAlert title="掌聲送給社會人" :closable='false' type='error'></zkxAlert>
    <zkxAlert title="馬上下班" type='warning'>周末愉快</zkxAlert>

 


免責聲明!

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



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