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>

你可能感兴趣的:(vue3,v-model)