vue3.js 3.3.x 发布新特性之 defineModel

作者: tww844475003 分类: 前端开发 发布时间: 2023-08-14 11:45
  • 以前,为了使组件支持与v-model双向绑定,它需要(1)声明prop,(2)在打算更新prop时发出相应的update:propName事件:
<script lang="ts" setup>
const props = defineProps([
  'modelValue'
])
const emits = defineEmits(['update:modelValue'])

const onInput = (e) => {
  emits('update:modelValue', e.target.value)
}
</script>

<template>
  <input :value="modelValue" @input="onInput" />
</template>
  • 新的defineModel宏的使用。宏会自动注册一个Props,并返回一个可以直接突变的引用:
<script setup lang="ts">
import { defineModel } from 'vue'

const inputVal = defineModel()
</script>

<template>
  <div class="custom-input">
    <input v-model="inputVal" type="text" />
  </div>
</template>

注意:直接使用 defineModel 宏会报错,需要开启。

完整示例代码

// 父组件
<script lang="ts" setup>
import { ref } from 'vue'
import CustomInput from './CustomInput.vue'

const inputValue = ref('hello defineModel')
</script>

<template>
  <div>
    <CustomInput v-model="inputValue"></CustomInput>
    <p>Input value: {{ inputValue }}</p>
  </div>
</template>

// CustomInput.vue
<script setup lang="ts">
import { defineModel } from 'vue'

const inputVal = defineModel()
</script>

<template>
  <div class="custom-input">
    <input v-model="inputVal" type="text" />
  </div>
</template>
前端开发那点事
微信公众号搜索“前端开发那点事”

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注