vue3的组件v-model初探1
父组件:
<template> <div class="about"> <v-input v-model="inp" type="text" /> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue' import vInput from '@/components/vInput.vue' export default defineComponent({ components: { vInput }, setup() { const inp = ref('111') return { inp } } }) </script>
子组件:
<template> <div> <input :value="val" @input="updateInput" > <div>{{ modelValue }}---{{ val }}</div> </div> </template> <script lang='ts'> import { defineComponent, ref } from 'vue' export default defineComponent({ name: 'vInput', props: { modelValue: String }, setup(props, context) { const val = ref(props.modelValue || '') const updateInput = (e: KeyboardEvent) => { val.value = (e.target as HTMLInputElement).value // context.emit('update:modelValue', (e.target as HTMLInputElement).value) context.emit('update:modelValue', val.value) } return { val, updateInput } } }) </script>