调用的子组件中使用v-model绑定数据以及使用@调用方法
- 手机
- 2025-09-13 14:27:02

实例:
子组件my-date-picker:
<!-- * @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>父组件:
<my-date-picker v-model="searchData.querydate" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" @customInput="search" />提示: 在子组件中使用v-bind="$attrs" v-on="$listeners"就能够绑定子组件中的所有属性和方法,父组件调用使用它也能够直接使用它的属性和方法。
调用的子组件中使用v-model绑定数据以及使用@调用方法由讯客互联手机栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“调用的子组件中使用v-model绑定数据以及使用@调用方法”
上一篇
Qt信号与槽机制