vue3的v-model写法

517 阅读1分钟

父级代码

<template>
  <!-- 这两个是一样的 v-model是语法糖 -->
  <Child v-model="childValue"/>
  <Child :modelValue="childValue" @update:modelValue="childValue=$event"/>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import Child from './child.vue'

const childValue = ref('')
</script>

子级代码

<template>
  <input type="text" :value="modelValue" @input="updateVal" />
</template>

<script lang="ts" setup>
import { reactive, ref, defineProps, defineEmits } from 'vue'

const props = defineProps<{
  modelValue: string,
}>()

//  2、定义emit名称,update+prop属性
const emit = defineEmits(['update:modelValue'])

// 3、绑定input事件,修改提交父组件修改属性值,checked事件同理
const updateVal = (e: Event) => {
  const targetVal = (e.target as HTMLInputElement).value
  emit('update:modelValue', targetVal)
}
</script>