如何在Vue.js中将v

编程入门 行业动态 更新时间:2024-10-27 20:32:05
本文介绍了如何在Vue.js中将v-model与嵌套属性一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经创建了一个表单,并且试图了解如何在Vue.js中使用带有嵌套属性的v-model

I have created a form and I'm trying to understand how to use v-model with nested properties in Vue.js

这是我模板的代码,如您所见,我正在尝试引用嵌套属性,如下所示: form.dobDate ,但是如何引用属性( dobDate , dobMonth 和 dobYear )在已安装和观看中?这样我输入的任何内容都会保留在页面刷新中?

This is the code for my template, as you can see I'm trying to reference the nested properties like so: form.dobDate, but how do I reference the properties (dobDate, dobMonth and dobYear) in mounted and watch? So that whatever I type remains there on page refresh?

<template> <div> <b-form novalidate> <b-form-select name="dobDate" id="dobDate" v-model="form.dobDate" :options="optionsDays"></b-form-select> <b-form-select name="dobMonth" id="dobMonth" v-model="form.dobMonth" :options="optionsMonths"></b-form-select> <b-form-input placeholder="Year of Birth" required autofocus class="form-control" name="year" id="year" min="0" max="2003" type="number" v-model="form.dobYear" ></b-form-input> <input type="text" v-model="name" /> <b-button type="submit" variant="primary">Submit</b-button> </b-form> <b-card class="mt-3" header="Form Data Result"> <pre class="m-0">{{ form }}</pre> </b-card> </div> </template>

这是脚本代码:

<script> export default { data() { return { name: "", form: { dobDate: { selected: "" }, dobMonth: { selected: "" }, dobYear: "", name: "" }, optionsMonths: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], show: true }; }, mounted() { if (localStorage.name) { this.name = localStorage.name; } }, watch: { name(newName) { localStorage.name = newName; }, deep: true }, computed: { optionsDays() { return Array.from(Array(31).keys()); } }, methods: { onSubmit(evt) { evt.preventDefault(); alert(JSON.stringify(this.form)); }, getDates() { return Array.from(Array(31).keys()); } } }; </script>

如您所见,我有一个表单对象,其中有要绑定的嵌套属性,我还使用了 mount ()和 watch 以便在刷新页面或提交表单时将数据存储在本地存储中(目前不进行验证).

As you can see I have a form object, with nested properties inside it which I want to bind to, and I'm also using mounted() and watch to store the data in local storage for when the page refreshes or when submitting the form (no validation at the moment).

推荐答案

您可以深入观察form(访问其嵌套字段)并使用:

You could watch the form deeply (accessing its nested field ) and loop through it values using :

Object.keys(after).forEach(key=>{ localStorage[key]=after[key] })

watch: { form: { handler: function(after, before) { Object.keys(after).forEach(key=>{ localStorage[key]=after[key] }) }, deep: true } }

更多推荐

如何在Vue.js中将v

本文发布于:2023-11-24 19:26:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626509.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   如何在   Vue   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!