vue3父子组件使用v-model双向绑定

一、方法

注意:
v-model:otherValue="state.otherValue" 可以实现同个组件绑定多个v-model
默认触发方式为update:modelValue
若自定义,则为自定义值, 如update:otherValue

父组件

<template>
	<div>
    	<Test v-model="state.msg" v-model:otherValue="state.otherValue"></Test>
  	</div>
</template>
<script setup lang="ts">
  const state = reactive({
     msg: '',
     otherValue: ''
  })
  watch(
    () => state.msg,
    () => {
      console.log(state.msg, '外部数据');
    },
    { deep: true }
  );
  watch(
    () => state.otherValue,
    () => {
      console.log(state.otherValue, '其他数据');
    },
    { deep: true }
  );
</script>

子组件

<template>
  <div>
    <input v-model="edit" placeholder="ttt" type="text" />
    <input v-model="otherValue" placeholder="info" type="text" />
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, computed, onMounted } from 'vue';
  const emits = defineEmits(['update:modelValue', 'update:otherValue', 'click', 'blur', 'focus', 'change', 'input', 'clear']);
  const props = defineProps({
    // 值
    modelValue: {
      type: String,
      default: ''
    },
    otherValue: {
      type: String,
      default: ''
    }
  });

  const edit = ref(props.modelValue);
  const otherValue = ref(props.otherValue);

  watch(
    [() => props.modelValue, () => edit.value],
    (n: any, o: any) => {
      if (n[0] !== o[0]) {
        edit.value = props.modelValue;
      }
      if (n[1] !== o[1]) {
        emits('update:modelValue', edit.value);
      }
    },
    { deep: true }
  );
  watch(
    [() => props.otherValue, () => otherValue.value],
    (n: any, o: any) => {
      if (n[0] !== o[0]) {
        otherValue.value = props.otherValue;
      }
      if (n[1] !== o[1]) {
        emits('update:otherValue', otherValue.value);
      }
    },
    { deep: true }
  );
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值