首页 > 解决方案 > 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

标签: vue.jsv-model

解决方案


您只是错过了添加valueTextField 组件道具的最后一部分。

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


推荐阅读