组件通信方式之V-model
上代码ba
父组件
<script setup lang="ts">
//v-model指令:收集表单数据,数据双向绑定
//v-model也可以实现组件之间的通信,实现父子组件数据同步的业务
//父亲给子组件数据 props
//子组件给父组件数据 自定义事件
import { ref } from "vue";
import Child1 from "./Child1M.vue";
import Child2 from "./Child2M.vue";
let money = ref(10000);
let addMoney = () => {
money.value += 100;
};
let handler = (num) => {
money.value += num;
};
let num1 = ref(200);
let num2 = ref(400);
let handle2 = () => {
num1.value += 10;
num2.value += 10;
};
<template>
<div class="container">
<div>money:{{ money }}</div>
<input type="text" v-model="money" />
<div>num1:{{ num1 }} num2:{{ num2 }}</div>
<button @click="handle2">增加num1 num2</button>
<br />
<hr />
<!-- props:父亲给儿子数据 -->
<!-- <Child :modelValue="money" @update:modelValue="handler"></Child> -->
<!--
v-model组件身上使用
第一:相当有给子组件传递props[modelValue] = 10000
第二:相当于给子组件绑定自定义事件update:modelValue
-->
<Child1
:money="money"
@addMoney="addMoney"
@update:modelValue="handler"
></Child1>
<Child2 v-model:num1="num1" v-model:num2="num2" @handle2="handle2"></Child2>
</div>
</template>
<style scoped></style>
</script>
子组件1
<script setup lang="ts">
const props = defineProps(["money"]);
const event = defineEmits(["addMoney", "update:modelValue"]);
</script>
<template>
<div class="container">
<h1>子组件1</h1>
<div>钱数:{{ money }}</div>
<button @click="event('addMoney')">addMoney点击增加钱数</button>
<button @click="event('update:modelValue', 1)">
update:modelValue点击增加钱数
</button>
</div>
</template>
<style scoped>
.container {
width: 300px;
height: 300px;
background: pink;
}
</style>
子组件2
<script setup lang="ts">
let props = defineProps(["num1", "num2"]);
let emit = defineEmits(["handle2"]);
</script>
<template>
<div class="container">
<h1>子组件2</h1>
<div>num1:{{ num1 }}</div>
<div>num2:{{ num2 }}</div>
<button @click="emit('handle2')">修改num1 num2</button>
</div>
</template>
<style scoped>
.container {
width: 300px;
height: 300px;
background: skyblue;
}
</style>
总结
1.v-model在子组件身上使用:
第一:相当有给子组件传递props[modelValue]
= 10000
第二:相当于给子组件绑定自定义事件update:modelValue