Vue: a better way for sync and v-model

Created on 28 Apr 2017  ·  4Comments  ·  Source: vuejs/vue

What problem does this feature solve?

Right now,we need set a data filed or a computed prop for the component prop we wanted modify,we modify the data filed or a computed prop and emit a update event to parent,but it's complicated to decited where and when to emit it,and it's unnecessary,the framework can do it for us.

What does the proposed API look like?

We can specify a binding data prop when using props, like this:
javascript <xxx :value.sync="parentValue"></xxx> export default = { props: { value: { type: String, default: 'foo', bind: 'innnerValue' } } } <xxx v-model="parentValue"></xxx> export default = { props: { value: { type: String, default: 'foo', bind: 'innnerValue' } }, model: { prop: 'value' } }
then it can generate a field called 'innnerValue' on this.$data and its defalut value is 'foo',when we modify this.innnerValue,the framework can emit a 'update:value' event automatically.And,if you modify the prop 'value' by parent,it also will update to innnerValue.You can use 'sync' to accept the change,you also can use 'v-model' after you specify model.prop.

feature request

Most helpful comment

Just create a computed getter/setter:

export default {
    prop: {
        model: 'value',
        event: 'input'
    },
    computed: {
        internalValue: {
            get() { return this[this.$options.prop.model] },
            set(v) { this.$emit(this.$options.prop.event, v) }
        }
    }
}

Within your component, use this.internalValue instead of this.value.

All 4 comments

It's not complicated to decide when to emit 🙂: $emit in the component whenever the value changes.
I really think it's a bad idea to complexify the API to add magic for something is already feasible quite easily. If better if the user understands the mechanism that is underneath to fully use the feature.

This is not going to happen - as explained, if a child component wants to affect parent state it has to do it explicitly. This is important for long term maintainability.

another better way: fjc0k/vue-better-sync

Just create a computed getter/setter:

export default {
    prop: {
        model: 'value',
        event: 'input'
    },
    computed: {
        internalValue: {
            get() { return this[this.$options.prop.model] },
            set(v) { this.$emit(this.$options.prop.event, v) }
        }
    }
}

Within your component, use this.internalValue instead of this.value.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

robertleeplummerjr picture robertleeplummerjr  ·  3Comments

aviggngyv picture aviggngyv  ·  3Comments

julianxhokaxhiu picture julianxhokaxhiu  ·  3Comments

guan6 picture guan6  ·  3Comments

finico picture finico  ·  3Comments