Skip to content

[vue] vue父子组件双向绑定的方法有哪些? #347

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

[vue] vue父子组件双向绑定的方法有哪些?

Activity

zyronon

zyronon commented on Jul 7, 2019

@zyronon

自己封装v-model

xunbie

xunbie commented on Jul 19, 2019

@xunbie

1.利用对象的引用关系来实现
2.父子组件之间的数据传递
3.使用.sync修饰符

Cai-zhiji

Cai-zhiji commented on Jul 7, 2023

@Cai-zhiji

使用v-model指令: v-model是Vue提供的语法糖,用于在组件之间实现双向绑定。在子组件中,可以通过props接收父组件传递的值,并使用$emit方法触发自定义事件将更新后的值传递回父组件。

<!-- 父组件 -->
<template>
  <div>
    <ChildComponent v-model="dataValue" />
  </div>
</template>

<!-- 子组件 -->
<template>
  <input :value="value" @input="$emit('input', $event.target.value)" />
</template>

<script>
export default {
  props: ['value'],
};
</script>

在父组件中,可以使用v-model来绑定子组件的值,实现双向绑定。

使用.sync修饰符: .sync修饰符是Vue提供的另一种简化父子组件双向绑定的方式。它通过自动生成一个名为update:xxx的属性和触发事件来实现双向绑定。

<!-- 父组件 -->
<template>
  <div>
    <ChildComponent :value.sync="dataValue" />
  </div>
</template>

<!-- 子组件 -->
<template>
  <input :value="value" @input="$emit('update:value', $event.target.value)" />
</template>

<script>
export default {
  props: ['value'],
};
</script>

在父组件中,使用:value.sync将子组件的值绑定到父组件的属性上,并在子组件中使用$emit('update:value', newValue)来触发更新。

使用自定义事件: 可以在父组件中使用自定义事件来接收子组件的更新,并通过事件参数获取子组件的新值。

<!-- 父组件 -->
<template>
  <div>
    <ChildComponent @updateValue="dataValue = $event" :value="dataValue" />
  </div>
</template>

<!-- 子组件 -->
<template>
  <input :value="value" @input="$emit('updateValue', $event.target.value)" />
</template>

<script>
export default {
  props: ['value'],
};
</script>

在子组件中,通过$emit('updateValue', newValue)触发自定义事件,并在父组件中通过@updateValue="dataValue = $event"来接收子组件的更新。

以上是几种常见的父子组件双向绑定的方法。根据具体的项目需求和开发场景,可以选择合适的方式来实现双向绑定。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@zyronon@xunbie@Cai-zhiji

        Issue actions

          [vue] vue父子组件双向绑定的方法有哪些? · Issue #347 · haizlin/fe-interview