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>

 

posted @ 2021-04-28 10:50  shine_lovely  阅读(144)  评论(0编辑  收藏  举报