调用的子组件中使用v-model绑定数据以及使用@调用方法

实例:

子组件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"就能够绑定子组件中的所有属性和方法,父组件调用使用它也能够直接使用它的属性和方法。

相关推荐
mCell11 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip11 小时前
Node.js 子进程:child_process
前端·javascript
excel14 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel16 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼17 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping17 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙18 小时前
[译] Composition in CSS
前端·css
白水清风18 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix18 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780018 小时前
new、原型和原型链浅析
前端·javascript