vue3在父子组件使用v-model双向绑定

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

父组件:

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

const count = ref(100)
</script>

<template>
  <div>
    我是父组件, {{ count }}
    <InputBox v-model="count"></InputBox>
    <!-- 在vue3的子父组件中使用v-model相当于下面这行代码 -->
    <!--<InputBox :modelValue="count" @update:modelValue="count=$event"></InputBox>-->

    <!-- vue2就相当于这行代码:-->
    <!-- <InputBox :value="count" @input="count=$event"></InputBox> -->
    <!-- vue2就有时候你并不想传递给子组件的props叫value,此时会用.sync修饰符:-->
    <!-- <InputBox :myvalue.sync="count"></InputBox> -->
    <!-- .sync就相当于下面这行代码,等同于简化了代码的编写。 -->
    <!-- <InputBox :myvalue="count" @update:myvalue="count=$event"></InputBox> -->
    
    <!-- 然后对比一看。。。其实vue3中的v-model就是和.sync是一个球样... -->
  </div>
</template>

封装一个InputBox子组件,用于数据的加减

<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)
}
</script>

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

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

思考:

觉得每次在子组件中定义emit和props很麻烦?vue3.3添加了一个实验性特新defineModel,详细见下一篇笔记。