vue.js - Vue v-model 未显示正确的默认值
问题描述
我的 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
解决方案
您只是错过了添加value
TextField 组件道具的最后一部分。
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
推荐阅读
- ios - 有时 VNDetectFaceLandmarksRequest 失败并出现未指定的错误
- javascript - 在 Combobox onload LWC 中默认一个动态值
- javascript - 如何使用javascript在对象和数组的深层嵌套数组中获取具有特定值的孩子的父母?
- python - 如何根据反转的字典值修改 Pandas DataFrame?
- python - 从搁置文件中删除所有键(使用 Python 自动化无聊的东西 - 第 9 章 - 扩展多剪贴板)
- android - 无法解析很多android库?
- python - 方法内部的 Pickle 类实例
- python - 如何将 numpy.ndarray 中的值写入 Dataframe?
- javascript - 在 React js 中出现此错误的原因是什么 - TypeError: this.state.data.map is not a function
- python - 如何将另一个 python 项目作为子模型添加到我的项目中?