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

相关推荐
No8g攻城狮1 天前
【前端】Vue 中 const、var、let 的区别
前端·javascript·vue.js
文心快码BaiduComate1 天前
Comate搭载Kimi K2.6,长程13h!
前端·后端·程序员
豹哥学前端1 天前
新手小白学前端day4: Position定位
前端
fishmemory7sec1 天前
Vue大屏自适应容器组件:v-scale-screen
前端·javascript·vue.js
饺子不吃醋1 天前
Promise原理、手写与 async、await
前端·javascript
PILIPALAPENG1 天前
第3周 Day 2:Function Calling —— 让 Agent 听懂人话,自己干活
前端·人工智能·python
前端那点事1 天前
Vue3+TS 中 this 指向机制全解析(实战避坑版)
vue.js
袋鼠云数栈UED团队1 天前
基于 OpenSpec 实现规范驱动开发
前端·人工智能
JarvanMo1 天前
GetX 作者的 GitHub 账号被封,又默默恢复了——但问题远没有解决
前端
大黄说说1 天前
HTML5语义化标签:从div到article与section的进化之路
前端·html·html5