在多次使用到相同的函数和相同的HTML代码时,可以考虑抽取为组件。想用就调用,想改就传参,就是组件的好处。
什么是组件
用面向对象的思维去理解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>
外界调用组件时添加自定义函数@getPerson
或v-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,呈现的效果如下:
© 版权声明
THE END
暂无评论内容