【问题标题】:Reset placeholder to default in a Vue JS form after submission提交后在 Vue JS 表单中将占位符重置为默认值
【发布时间】:2020-04-11 10:32:00
【问题描述】:

我想在我正在构建的样本生成器中重置名称值,在样本发布后,但努力让它正确。首先,应用程序中的所有值,2 种颜色和样本名称,都被观察和发出。这是名称值(value3),但颜色设置相同,只是 value1value2(不重置颜色)

<b-form-input
        id="name"
        size="lg"
        type="text"
        class="search-bar"
        placeholder="Name Your Swatch and Enter to Save"
        v-model="value3"
        ref="value3"
        :value="value3"
        @keypress="publishSwatch"
        >
</b-form-input>

而收集名字的就在这里:

props: ['value'],
publishSwatch(e) {
  this.$emit('input', {
    value3: +this.$refs.value3.value,
  });
  if (e.key == "Enter") {
    this.createSwatch();
    this.resetForm(); //Not done yet
    this.handleSwatch();
  }
}

createSwatch 函数的相关工作部分只是:

let name = (`${this.value3}`);  //this works fine to set and output the inputted value
resetForm() {
// Stuck for what to put here
}

样本发布后,我想在resetForm()函数中将占位符重置为默认值,我可以将其放置在publishSwatch方法中的相关位置,应该如上,但无法靠近做对了。颜色在另一个函数中,而不是重置那些。我已经尝试过了,但它似乎与输入的设置方式无关:

resetForm() {
    let clear = document.getElementById('name');
    clear.input.value.reset();
}

而且不工作

欢迎提示。

谢谢

【问题讨论】:

  • 默认占位符是什么意思?

标签: javascript html vue.js vuejs2 vue-component


【解决方案1】:
  • 不要同时使用:valuev-model,因为v-model 会自动创建:value,这样会产生冲突。
  • 不需要ref,因为正确的方法是在实例中使用v-model 绑定(value3) 而不是DOM 值

HTML

<b-form-input
    id="name"
    size="lg"
    type="text"
    class="search-bar"
    placeholder="Name Your Swatch and Enter to Save"
    v-model="value3"
    @keypress="publishSwatch">
</b-form-input>

方法应该如下所示:

methods: {
  publishSwatch(e) {
    this.$emit('input', {
      value3: +this.value3
    });
    if (e.key == "Enter") {
      this.createSwatch();
      this.resetForm();
      this.handleSwatch();
    }
  },
  resetForm() {
    this.value3 = ''; // <-- Reset the instance value
  }
}

这是demo

【讨论】:

  • 好的,所以我实际上不必使用 :value 和 refs,我会试试 thyanks
  • 不客气。是的,当使用绑定值无法轻松完成某些事情时,refs 非常适合操作 DOM。例如,将焦点设置在模板元素上。
  • 顺便说一句,这个有问题,它停止工作,它看起来 OIk 但没有重置值,知道为什么/这是当前代码。
  • 这个有问题,它停止工作,它看起来 OIk 但没有重置值,知道为什么/这是当前代码。 data() { return { value3: null } }, methods: { // 将表单重置为默认值 resetForm() { this.value3 = ''; if(this.value3 == '') { console.log('RESET'); } },然后在函数 publishSwatch(e) { if (e.key == "Enter") { console.log('EMIT'); this.$emit('input', { value3: +this.value3 }); this.createSwatch(); this.resetForm(); this.handleSwatch(); } }
  • 它似乎已更改为仅在按 Enter 时发射。它仍然清除:jsfiddle.net/sh0ber/35p0gmL1
猜你喜欢
  • 2013-04-15
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 2014-04-22
  • 2017-05-11
  • 1970-01-01
  • 2020-12-12
  • 2013-07-21
相关资源
最近更新 更多