我的Vue应用程序中有一个可重用的TextField
组件。现在,我想拥有一个表单,在该表单中我首先获取一些用户数据,然后以该表单显示它,以便用户可以编辑其数据。除了没有显示TextField
中的值之外,其他所有东西都工作正常。当我单击“提交”按钮时,它确实向我显示了警报中的正确值。但是,它不会在表单输入中显示值。
我猜想这仅与我的TextField组件中的v-model
有关localValue
:
<template>
<v-text-field
v-model="localValue"
:rules="rules"
:counter="counter"
:label="label"
:required="required"
:placeholder="placeholder"
:type="type"
></v-text-field>
</template>
<script>
export default {
name: "TextField",
props: {
rules: Array,
counter: Number,
label: String,
required: {
type: Boolean,
default: true
},
placeholder: String,
type: {
type: String,
default: "text"
}
},
data: () => ({
localValue: ""
}),
created() {
this.localValue = this.value;
this.$watch("localValue", value => {
this.$emit("input", value);
});
}
};
</script>
我创建了一个CodeSandBox来向您展示我的代码,也许有人可以向我解释为什么它无法按我预期的那样工作。
https://codesandbox.io/s/exciting-currying-yvbp3?fontsize=14&hidenavigation=1&theme=dark
答案 0 :(得分:3)
您只是错过了在TextField Component的道具中添加value
的最后一部分。
export default {
name: "TextField",
props: {
rules: Array,
counter: Number,
label: String,
required: {
type: Boolean,
default: true
},
placeholder: String,
type: {
type: String,
default: "text"
},
value:String
},
data: () => ({
localValue: ""
}),
created() {
this.localValue = this.value;
this.$watch("localValue", value => {
this.$emit("input", value);
});
}
};