我不明白v-bind
,v-model
和v-bind.sync
之间有什么区别
也许为时已晚,但在阅读了文档之后,我无法分辨v-bind.sync
和v-model
之间的区别。
示例
我使用"vue-property-decorator“在打字稿中编写了以下组件。我不知道如何更新传递到组件中的date
对象,而不必自己编写事件。如果您问我,它应该使用v-model
和v-bind.sync
绑定(以及标记和装饰器中的相应更改)。
HTML
<Datepicker v-model="date"/>
打字本
import { Component, Prop, Vue, Model } from "vue-property-decorator";
@Component({})
export default class Datepicker extends Vue {
@Prop()
private label!: string;
@Model()
private date!: Date;
private internalDate = new Date().toISOString().substr(0, 10);
private menu = false;
private onDateChanged() {
const isoDate = this.date.toISOString();
const newDate =
this.internalDate + this.date.toISOString().substring(10);
this.date = new Date(newDate);
}
}
每次更改this.date
对象时,都会收到警告:
避免直接更改支柱,因为每当父组件重新呈现时,值都会被覆盖。相反,使用基于支柱值的数据或计算属性。道具变异:“日期”
发布于 2019-01-05 07:55:22
在Vue.js中,不应该改变组件传递给您的输入prop
。例如,在您的例子中,请考虑label
支柱。在您的DatePicker
中,不应该有任何像this.label = 'Hello! Change Prop!';
这样的语句。
TLDR:不要改变组件中的支柱。让父母变异吧。
回到您的组件,您应该有这样一个组件:
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
@Component({})
export default class Datepicker extends Vue {
@Prop()
private label!: string;
@Prop()
private value!: Date;
private internalDate = new Date().toISOString().substr(0, 10);
private previouslyEmittedDate: Date;
private menu = false;
@Watch('value')
public onDatePropChange() {
// Break infinite one-way recursion
if (this.value !== this.previouslyEmittedDate) {
const newDate = new Date(this.internalDate + this.value.toISOString().substring(10));
this.previouslyEmittedDate = newDate;
// input events created a sugar coated v-model binding
this.$emit('input', newDate);
}
}
}
作为附带说明:--我注意到这里有某种代码气味。在每次更改日期时,您都要添加一些内部日期。它将导致无限的单向绑定递归。v-model
用于用户更改的input
,而不是编程更改的。v-model
只是用于以下内容的糖衣语法:
<Datepicker :value="date" @input="this.date = $event"/>
最后,避免使用.sync
修饰符。它有着不同的用途,应该谨慎使用。
https://stackoverflow.com/questions/54044927
复制相似问题