likes
comments
collection
share

vue3 组件通信 --- v-model

作者站长头像
站长
· 阅读数 11

此文章介绍使用 v-model 实现父子组件数据同步,原理为:在子组件标签上绑定属性和自定义事件,子组件内部使用 definePropsdefineEmits 接收属性和自定义事件,且子组件内部使用接收的自定义事件修改接收到的属性值,然后父组件根据绑定的自定义事件接收到子组件传递过来的新数据,从而实现父子组件数据同步。

不使用 v-model 实现

Parent.vue

<template>
    <div>我是父组件</div>
    <pre>我是父子组件同步的数据:{{ money }}</pre>
    <Child :modelValue="money" @update:modelValue="handler"></Child>
</template>

<script setup>
import { ref } from "vue";
import Child from "./Child.vue";

const money = ref(10000);

const handler = (val) => {
    money.value = val;
};
</script>

Child.vue

<template>
    <div>我是子组件</div>
    <pre>父组件给我的数据:{{ modelValue }}</pre>
    <button @click="handler">点我改变接收到的数据</button>
</template>

<script setup>
const props = defineProps(['modelValue'])
const $emits = defineEmits(['update:modelValue'])

const handler = () => {
    $emits('update:modelValue', props.modelValue + 1000)
}
</script>

使用 v-model 实现

只需要在父组件中更改

<template>
    <div>我是父组件</div>
    <pre>我是父子组件同步的数据:{{ money }}</pre>
+++    <Child v-model="money"></Child>
---    <Child :modelValue="money" @update:modelValue="handler"></Child>
</template>

<script setup>
import { ref } from "vue";
import Child from "./Child.vue";

const money = ref(10000);

--- const handler = (val) => {
---    money.value = val;
--- };
</script>

绑定多个 v-model

Parent.vue

<template>
  <div>我是父组件</div>
  <pre>我是父子组件同步的数据:{{ pageNo }} --- {{ pageSize }}</pre>
  <Child v-model:pageNo="pageNo" v-model:pageSize="pageSize"></Child>
</template>

<script setup>
import { ref } from "vue";
import Child from "./Child.vue";

const pageNo = ref(10000);
const pageSize = ref('hello vue!')

</script>

Child.vue

<template>
    <div>我是子组件</div>
    <pre>父组件给我的数据:{{ pageNo }} --- {{ pageSize }}</pre>
    <button @click="() => $emits('update:pageNo', pageNo + 1000)">点我改变接收到的数据1</button>
    <button @click="() => $emits('update:pageSize', 'hello world!')">点我改变接收到的数据2</button>
</template>

<script setup>
const props = defineProps(['pageNo', 'pageSize'])
const $emits = defineEmits(['update:pageNo', 'update:pageSize'])
</script>

vue3 组件通信 --- v-model

总结

  • vue2 中的 v-model 实现相当于给子组件绑定了 value 属性,和 input 事件
  • vue3 中的 v-model 实现相当于给子组件绑定了 modelValue 属性,和 updata:modelValue 自定义事件