使用观察程序动态更改表单数据



好吧,所以我很累,我知道我做错了什么(更重要的是它不起作用,哈哈(,但我看不见。所以,情况就是这样。用户在中填写了3个字段

  • 月份
  • 年份

然后需要将其组合成Y-m-d格式的正式日期并存储在表格中。生日

我认为使用Vue Watcher是解决方案,但。。。当有人填写表格时,它似乎不会更新表格。生日会导致一个错误";未找到出生日期"-然而,如果我在Vue DevTools中将watch更改为computed on dev,如果我打开它,它会立即填充数据。

我缺少的应该是在用户键入时更新特定的表单数据对象/字符串。

watch: {
getBirthdate: function () {
let birthdate = `${this.birthdate.year}-${this.birthdate.month}-${this.birthdate.day}`;
this.form.birthdate = birthdate;
},
},

由于v-modeltwo-way绑定,这意味着如果更改输入值,则绑定的数据将更改。因此,Values将自动更新,但如果您希望在没有任何显式方法调用的情况下组合这些daymonthyear,则可以通过使用computed属性来实现。

实时演示

new Vue({
el: '#app',
data: {
birthdate: {
day: '',
month: '',
year: ''
}
},
computed: {
combinedBirthDate: function() {
let birthDate = `${this.birthdate.year}-${this.birthdate.month}-${this.birthdate.day}`;
return birthDate;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<form>
<label>Day</label>
<input type="text" name="day" v-model="birthdate.day"><br>
<label>Month</label>
<input type="text" name="month" required v-model="birthdate.month"><br>
<label>Year</label>
<input type="text" name="year" v-model="birthdate.year">
</form>
<pre>{{ birthdate }}</pre>
<pre>{{ combinedBirthDate }}</pre>
</div>

最新更新