vue3.3实验性新特性defineModel

发布时间 2023-08-12 15:21:41作者: 蕝戀

子父之间使用v-model双向绑定数据,子组件每次都要写emit和props觉得麻烦?

vue3.3新的实验性特性defineModel可以完全不写emit和props。

由于是实验性特性,所以需要配置之后才能使用。

修改vite.config.js:

export default defineConfig({
  plugins: [
    vue(**{
      script: {
        defineModel: true
      }
    }**),
  ],
...

测试案例:

子组件InputBox.vue

<script setup>
// 1. 和vue2一样,先通过props接收数据
// const props = defineProps(['modelValue']);
// 2. 和vue2一样,也是要使用emit来触发父组件的事件
// const emits = defineEmits(['update:modelValue']);
// const ChangeNum = (num) => {
//   emits('update:modelValue', props.modelValue+num)
// }

// 直接定义一个名叫modelValue的,via: v-model
const modelValue = defineModel()

// via:v-model:haha=xxxxx (绑定多个v-model时,可以指定name)
const haha = defineModel('haha')
</script>

<template>
  <div class="son">
    <button @click="modelValue--">-</button>
    <input style="width: 50px;" type="text" :value="modelValue">
    <input style="width: 50px;" type="text" :value="haha">
    <button @click="modelValue++">+</button>
  </div>
</template>

<style scoped>
.son {
  border: 1px solid red;
  padding: 30px;
  width: 300px;
}
</style>

父组件:

<script setup>
import InputBox from "@/compon/InputBox.vue";
import {ref} from "vue";

const count = ref(100)
const num = ref(50)
</script>

<template>
  <div>
    我是父组件, {{ count }}
    <InputBox v-model:haha="count" v-model="count"></InputBox>
  </div>
</template>