Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
haizhilin2013 opened this issue Jun 20, 2019 · 3 comments
Open

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

haizhilin2013 opened this issue Jun 20, 2019 · 3 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

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

@haizhilin2013 haizhilin2013 added the vue vue label Jun 20, 2019
@zyronon
Copy link

zyronon commented Jul 7, 2019

自己封装v-model

@xunbie
Copy link

xunbie commented Jul 19, 2019

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

@Cai-zhiji
Copy link

使用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
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

4 participants