【发布时间】:2020-11-17 09:47:17
【问题描述】:
在线程Which limitations v-model has in Vue 2.x? 中,我学习了如何链接父组件和子组件v-model。 suggested solution 是:
--- ParentTemplate:
<Child v-model="formData"></Child>
-- ChildTemplate:
<input v-model="localValue">
-- ChildScript:
computed: {
localValue: {
get() {
return this.value;
},
set(localValue) {
this.$emit('input', localValue);
},
},
},
不幸的是,我无法将其重写为 vue-class-component 语法。下面的代码既不工作也不应该工作:
export default class TextEditor extends Vue {
@Prop({ type: String, required: true }) private readonly value!: string;
private get localValue(): string {
return this.value;
}
private set localValue(newValue: string) {
this.$emit("input", newValue);
}
}
how to write computed setters in class-based components in vuejs 问题的答案不适用于 vue 组件属性,因为属性是只读的。所以我不能写this.value = newValue。
直接使用value 的问题##
<EditorImplementation
:value="value"
@input="(value) => { onInput(value) }"
/>
@Component({
components {
EditorImplementation: CK_Editor.component
}
})
export default class TextEditor extends Vue {
@Prop({ type: String, required: true }) private readonly value!: string;
@Emit("input")
private onInput(value: string): void {
console.log("checkpoint");
console.log(this.value);
}
}
假设初始值为空字符串。
- 输入“f”
- 日志将是
"checkpoint" "" - 输入“a”
- 日志将是
"checkpoint" "f" - 输入“d”
- 日志将是
"checkpoint" "fa"
等等。
【问题讨论】:
-
我认为这不是最好的方法。你不应该直接改变道具。为什么不能直接将
value道具放在模板中。类似<input :value="value"> -
@Tony,谢谢你的回答。使用
EditorImplementation(:value="value" @input="(value) => { onInput(value) }"),在@Emit("input") private onInput(value: string): void { console.log(this.value); }中,我总是得到以前的value的输出,而不是实际的。例如。在第一次输入时,value仍然是空字符串。正常吗? -
您好,请编辑帖子并添加此功能以提高可读性。
-
@Tony,Roger,完成了。
标签: typescript vue.js vuejs2 vue-class-components vue-property-decorator