vue3组件的双向绑定

// 父组件
<template>
  <div>
  	<!-- 默认 v-model:modelValue="inputValueProp" modelValue可自定义用于多个监听值(父组件也要更改) -->
    <BindingInput v-model="inputValueProp"></BindingInput>
    {{inputValueProp}}
  </div>
</template>

<script>
import { ref } from 'vue'
import BindingInput from './components/BindingInput.vue'
export default {
  name: "App",
  components: {
    BindingInput
  },
  setup () {
    const inputValueProp = ref('logan')
    return {
      inputValueProp
    }
  }
};
</script>
// 子组件(旧)
<template>
  <input :value="inputValue" @input="upDateValue" />
</template>

<script>
import { ref } from 'vue'

export default {
  name: "BindingInput",
  props: {
    modelValue: String
  },
  setup (props, context) {
    const inputValue = ref(props.modelValue || '')
    const upDateValue = (e) => {
      const targetValue = e.target.value
      inputValue.value = targetValue
      context.emit('update:modelValue', targetValue)
    }
    return {
      inputValue,
      upDateValue
    }
  }
};
</script>

==========二更
发现使用computed可以使用更少的代码完成一样的问题

// 子组件 新
<template>
  <input v-model="inputValue" />
</template>

<script>
import { computed } from 'vue'

export default {
  name: "BindingInput",
  props: {
    modelValue: String
  },
  setup (props, context) {
    const inputValue = computed({
      get: () => props.modelValue || '',
      set: val => {
        context.emit('update:modelValue', val)
      }
    })
    return {
      inputValue,
    }
  }
};
</script>

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐