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.
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.
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.
Most helpful comment
Just create a computed getter/setter:
Within your component, use
this.internalValueinstead ofthis.value.