vue2 组件封装
本文记录一下 Vue 组件封装的基本实践和一些组件的相关知识。主要涉及以下知识点:
- 封装一个组件的代码组织形式;
- vue 组件的三大核心:
- 属性(props、data);
- 事件
- 插槽
- 样式
- 其他一些杂项
- $nextTick 函数的使用
- 获取 DOM 元素及在父级组件中执行子组件方法
使用第三方计数库 countup.js 创建一个 count-to
组件对以上知识进行总结。
文件组织形式
在组件文件夹 component
下创建一个与组件名相同的文件,文件夹内必须有 index.js
, 并将组件导入到该文件中,这样方便我们引用组件。
count-to
文件夹内:
// index.js
import CountTo from './count-to.vue'
export default CountTo
使用组件时,只需这样引入:
import CountTo from '_c/count-to' // _c 是组件存放路径
Vue 组件的三大核心
属性(props、data 和样式)
props 定义了组件 可配置
的数据,确定的组件的核心功能。封装组件时,props 推荐写成对象形式,方便对数据进行验证,提高了代码健壮性也能明确如何使用。
常见的检查类型: Number
、 String
、 Boolean
、 Array
、 Object
、 Date
、 Function
、 Symbol
、 构造函数
。 null|undefined
会通过所有类型。
还可以自定义验证函数,指定是否必须和默认值。
props: {
// 多个可能的类型
propB: [String, Number],
// 必填的字符串
propC: {
type: String,
required: true
},
// 带有默认值的数字
propD: {
type: Number,
default: 100
},
// 带有默认值的对象
propE: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default: function() {
return {
message: 'hello'
}
}
},
// 自定义验证函数
propF: {
validator: function(value) {
// 这个值必须匹配下列字符串中的一个
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
通过阅读 countUP 文档,了解到构造函数 CountUp
的参数
CountUp(eleDOM, startValue, endValue, decimals, duration, options) // eleDOM 是数值显示的元素;endValue 是数值的最终值,这两个参数必须的。
组件代码如下:
<template>
<div>
<span :id="eleId"></span>
</div>
</template>
<script>
import CountUp from 'countup'
export default {
name: 'CountTo',
props: {
/**
* @description 起始值
*/
startValue: {
type: Number,
default: 0
},
/**
* @description 终止值
*/
endValue: {
type: Number,
required: true
},
/**
* @description 小数点后保留几位小数(精度)
*/
decimals: {
type: Number,
default: 0
},
/**
* @description 渐变时长(秒)
*/
duration: {
type: Number,
default: 1
},
/**
*@description 变速效果
*/
useEasing: {
type: Boolean,
default: false
},
/**
*@description 分组
*/
useGrouping: {
type: Boolean,
default: true
},
/**
*@description 分组符号 2,2234
*/
separator: {
type: String,
default: ','
},
/**
*@description 整数小数分隔符 34.56
*/
decimal: {
type: String,
default: '.'
},
/**
* @description 动画延迟(秒)
*/
delay: {
type: Number,
default: 0
}
},
data() {
return {
}
},
computed: {
eleId() {
// 使用 this.uid 生成组件内唯一id
return `count_up_uid${
this._uid}`
}
},
mounted() {
// TODO: this.$nextTick
this.$nextTick(() => {
let options = {
useEasing: this.useEasing,
useGrouping: this.useGrouping,
separator: this.separator,
decimal: this.decimal
}
this.counter = new CountUp(this.eleId, this.startValue, this.endValue, this.decimals, this.duration, options)
})
}
}
</script>
代码说明:
this._uid
用于生成 组件内唯一
的 id 值,可用作元素的 id,值是递增的。
this.$nextTick
函数接收一个回调函数作为参数,回调函数会在 DOM更新
之后执行,如果某些操作必须在 DOM 更新之后,可将这些操作作为其参数。
计数组件的基本功能就满足了。
这样使用组件:
<template>
<div>
<count-to :end-value="endValue" :decimals="decimals" :duration="5" title="这个会挂载到组件根元素上"></count-to>
</div>
</template>
<script>
import CountTo from '_c/count-to'
export default {
name: 'count_to',
components: {
CountTo
},
data() {
return {
endValue: 4000,
decimals: 2,
className: ''
}
}
}
</script>