[Vue]組件是什么以及如何使用組件


什么是組件

用面向對象將所有的事物都抽象為對象,而類或組件,都具有屬性和方法。

比如,將人類抽取為組件,其基本的屬性有姓名、年齡、國籍,基本的方法有吃飯、睡覺、跑步。

<script>
export default {
    name: 'person',
    props: {
        name: {
            type: String,
            required: false,
            default: '無名氏'
        },
        age: {
            type: Number,
            required: false,
            default: 0
        },
        country: {
            type: String,
            required: false,
            default: '地球人'
        }
    },
    methods: {
        eat() {
            consloe.log('吃飯')
        },
        sleep() {
            consloe.log('睡覺')
        },
        run() {
            consloe.log('跑步')
        }
    }
}
</script>

在面向對象中,構造函數可以初始化類的屬性的值;在使用組件時,也可以初始化組件的屬性的值。

<person :age="20" :name="'小明'" :country="'中國人'"></person>

自定義事件

外界不可直接使用或訪問組件的屬性,該如何做?

使用$emit自定義事件,可以實現外界獲取組件的屬性。

<template>
    ......
    <button @click="handleClick">點擊</button>
</template>

<script>
export default {
    name: 'person',
    methods: {
        handleClick() {
            this.$emit('getPerson', {
                age: this.age,
                name: this.name,
                country: this.country
            })
        }
    }
}
</script>

外界使用組件時,為其添加自定義函數@getPersonv-on:click="getPerson"

<template>
    <person :age="20" :name="'小明'" :country="'中國人'" @getPerson="getPerson"></person>
</template>

<script>
export default {
    name: 'test',
    methods: {
        getPerson(info) {
            consloe.log(info)
        }
    }
}
</script>

實際案例

在網頁開發中,對於標簽,你可能會想到它不可能在一個頁面中使用,可能是在多個頁面中被多次使用,你還可能會想到因為不同的情況,它的寬度、高度和顏色等屬性都要發生變化。

因此,我們可以將一段重復使用到的代碼封裝為一個組件,組件對外提供width、height和type等屬性,在使用組件時,因不同的需求而改變組件的屬性的值。

<template>
    <view
        :style="{ width: width, height: height }"
        :class="['owl-tag-' + type]"
        class="owl-tag text-xs flex align-center justify-center"
    >
        <slot></slot>
    </view>
</template>

<script>
    name: 'owl-tag',
    props: {
        // 可傳入primary、gray
        type: {
            type: String,
            default: 'primary'
        },
        width: {
            type: String,
            required: false
        },
        height: {
            type: String,
            required: false
        }
    }
</script>

<style>
.owl-tag {
    border-radius: 8rpx;
    padding: 6rpx 10rpx;
}

.owl-tag-primary {
    color: white;
    background-color: #87cefa;
}

.owl-tag-gray {
    color: #81868a;
    background-color: #f0f1f5;
}
</style>

組件封裝完成,想用就用,想變就變,這就是組件的好處。

<template>
    <owl-tag
        :type="'primary'"
        :height="'45rpx'"
        :width="'120rpx'"
    >
        官方帖
    </owl-tag>
</template>

修改type屬性的值為gray,呈現的效果如下:


免責聲明!

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



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