实例:
子组件my-date-picker:
javascript
<!--
* @description: 日期组件二次封装
* 解决 "日期为区间时,后端不支持传数组,而要传#分割的字符串"
-->
<template>
<el-date-picker
class="comp-my-date-picker"
v-model="date"
v-bind="$attrs"
v-on="$listeners"
:value-format="valueFormat"
@change="change"
></el-date-picker>
</template>
<script>
export default {
name: 'my-date-picker',
model: {
prop: 'value',
event: 'customInput'
},
props: {
/** 双向绑定值 */
value: {
type: [String, Array],
default: ''
},
/** 当 type = daterange 时,数组拼接字符串所用的分隔符,默认# */
separator: {
type: String,
default: '#'
},
/** 双向绑定的值是否转换成以separator分割的字符串 */
convertToStr: {
type: Boolean,
default: true
}
},
watch: {
value: {
handler(val) {
if (val && val.split && val.split(this.separator).length === 2) {
this.date = val.split(this.separator)
} else {
this.date = val
}
},
immediate: true
}
},
computed: {
valueFormat() {
return this.$attrs['value-format'] || this.$attrs.type === 'datetime' || this.$attrs.type === 'datetimerange'
? 'yyyy-MM-dd HH:mm:ss'
: 'yyyy-MM-dd'
}
},
data() {
return {
date: null
}
},
created() {},
mounted() {},
methods: {
change(val) {
this.$emit('customInput', Array.isArray(val) && this.convertToStr ? val.join(this.separator) : val)
}
}
}
</script>
<style lang="less" scoped></style>
父组件:
html
<my-date-picker
v-model="searchData.querydate"
type="daterange"
start-placeholder="开始时间"
end-placeholder="结束时间"
@customInput="search"
/>
提示: 在子组件中使用v-bind="attrs" v-on="listeners"就能够绑定子组件中的所有属性和方法,父组件调用使用它也能够直接使用它的属性和方法。