什麼是元件

用面向物件的思維去理解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>
<div>
<person :age="20" :name="'小明'" :country="'中國人'" @getPerson="getPerson"></person>
</div>
</template> <script>
export default {
name: 'test',
methods: {
getPerson(info) {
consloe.log(info)
}
}
}
</script>

實際案例

在網頁開發中,你可能會用到標籤,而你可能會想到標籤不可能在一個頁面使用一次,可能是多次使用到。你還可能會想到因為不同的情況而自定義一些寬度、高度和顏色。

所以可以將標籤相關的HTML程式碼和CSS封裝到元件中,對外,我們暴露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,呈現的效果如下: