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

Vue2 .sync vs v-model #74

Open
vhxubo opened this issue Mar 3, 2022 · 0 comments
Open

Vue2 .sync vs v-model #74

vhxubo opened this issue Mar 3, 2022 · 0 comments

Comments

@vhxubo
Copy link
Owner

vhxubo commented Mar 3, 2022

.sync was added after we had added v-model for components and found that people often could use that v-model logic for more than one prop.

So they essentially do the same thing.
https://forum.vuejs.org/t/sync-vs-v-model/19380/2

首先抛出结论, v-model 是用于处理单个双向数据的简易方案, 而 .sync 可以同时绑定多个双向数据流

v-model

<!-- 父组件 -->
<div v-model="layout" />
<div :value="value" @input="value = $event" />
// 子组件
this.$emit('input', $event.target.value)

自定义 v-model 是有一定限制的, 需要实现默认的 input 事件, 以及默认绑定的 value 变量

.sync

<!-- 父组件 -->
<div :layout.sync="layout" />
<div :layout="layout" @update:layout="layout = $event" />
// 子组件
this.$emit('update:layout", this.layout)

多数据绑定案例

<div
    :layout.sync="layout"
    :table.sync="table"
    :xl.sync="xl"
    :yl.sync="yl"
/>
<div 
    :layout="layout"
    :table="table"
    :xl="xl"
    :yl="yl"
    @update:layout="layout = $event"
    @update:table="table = $event"
    @update:xl="xl = $event"
    @update:yl="yl = $event"
/>
this.$emit('update:layout', this.layout)
this.$emit('update:table', this.table)
this.$emit('update:xl', this.xl)
this.$emit('update:yl', this.yl)

在更新数据时, 我们可能也需要向 update 事件里面传入参数, 此时我们可以使用

<div
    :layout="layout"
    @update:layout="updateLayout('hello', $event)
/>
updateLayout(param, val) {
  console.log(param)
  console.log(val)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant