vue props +computed 子组件改变emit通知父组件 useVModel 简化版

在这里插入图片描述

useVModel.ts

import { computed, WritableComputedRef } from 'vue'

export function useVModel<T>(
  props: { [x: string]: any },
  propName: string,
  emit: (...args: any[]) => void,
): WritableComputedRef<T> {
  return computed({
    get() {
      if (Object.prototype.toString.call(props[propName]) === '[object Object]') {
        return new Proxy(props[propName], {
          set(obj, name, val) {
            emit(`update:${propName}`, Object.assign(obj, { [name]: val }))
            return true
          },
        })
      }
      return props[propName]
    },
    set(val) {
      emit(`update:${propName}`, val)
    },
  })
}

modelValue非对象使用方法

<template>
  <Switch v-model="model" />
</template>
 <script lang="ts" setup>
  import {
    defineEmits, defineProps,
  } from 'vue'
  import { Switch } from 'xxxxx'
  import { useVModel } from '~/hooks/useVModel'

  const emit = defineEmits(['update:modelValue'])
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
      require: true,
    },
  })
  const model = useVModel<any>(props, 'modelValue', emit)
</script>

modelValue对象使用方法

<template>
  <div class="account-business">
    <Form ref="$refs">
      <Field
        name="accountScene"
        required
        :rules="[{ required: true, message: '此项必填' }]"
      >
        <template #input>
          <AccountSelectType
            v-model="model.accountScene"
            :types-list="serviceList"
          />
        </template>
      </Field>
    </Form>
  </div>
</template>

<script setup lang="ts">
  import {
    ref, defineEmits, defineProps, PropType,
  } from 'vue'
  import { Form, Field } from 'xxxxx'
  import { useVModel } from '~/hooks/useVModel'
  import AccountSelectType from './AccountSelectType.vue'
  import {
    ACCOUNT_FORMVALUE, IAccountServiceItem,
  } from '~/services/xxxxxx'

  const props = defineProps({
    modelValue: {
      type: Object as PropType<ACCOUNT_FORMVALUE>,
      required: true,
    },
    serviceList: {
      type: Array as PropType<IAccountServiceItem[]>,
      default: () => ([]),
    },
  })
  const $refs = ref()
  const emit = defineEmits(['update:modelValue'])
  const model = useVModel<props的数据类型>(props, 'modelValue', emit)
  defineExpose({ $refs })
</script>

参考链接:https://vueuse.org/core/useVModel/

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值