英文:
Vue v-model not showing the right default values
问题
我在我的Vue应用中有一个可重用的TextField
组件。现在我想要创建一个表单,首先获取一些用户数据,然后在表单中显示这些数据,以便用户可以编辑它们。一切都正常,除了在TextField
中不显示值。当我点击'提交'按钮时,它确实在警报框中显示了正确的值。但是,在表单输入中不显示这些值。
我猜这可能与我的TextField
组件中仅使用localValue
的v-model
有关:
<template>
<v-text-field
v-model="localValue"
:rules="rules"
:counter="counter"
:label="label"
:required="required"
:placeholder="placeholder"
:type="type"
></v-text-field>
</template>
我创建了一个CodeSandBox来展示我的代码,也许有人可以解释为什么它没有按照我预期的工作。
英文:
I have a reusable TextField
component in my Vue application. I now want to have a form where I first fetch some user data and then display it in that form so the user can edit their data. Everything works fine except that it doesn't show the values in the TextField
. When I click on the 'submit' button it does show me the right values in the alert. However, it doesn't show the values in the form input.
I guess it has something to do with the v-model
only using the localValue
in my TextField component:
<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>
I created a CodeSandBox to show you my code, maybe someone can explain to me why it didn't work like I expected.
https://codesandbox.io/s/exciting-currying-yvbp3?fontsize=14&hidenavigation=1&theme=dark
答案1
得分: 3
你只需要在TextField组件的props中添加value
部分的代码。
props: {
rules: Array,
counter: Number,
label: String,
required: {
type: Boolean,
default: true
},
placeholder: String,
type: {
type: String,
default: "text"
},
value: String // 在这里添加 value 属性
},
工作代码示例:https://codesandbox.io/s/great-waterfall-nbm4o
英文:
You just miss the last part to add value
in props of TextField Component.
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);
});
}
};
wokring codepen- https://codesandbox.io/s/great-waterfall-nbm4o
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论