什么是组件
用面向对象将所有的事物都抽象为对象,而类或组件,都具有属性和方法。
比如,将人类抽取为组件,其基本的属性有姓名、年龄、国籍,基本的方法有吃饭、睡觉、跑步。
<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>
外界使用组件时,为其添加自定义函数@getPerson
或v-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,呈现的效果如下: