我的Vue.js组件中包含以下代码:
mounted() {
if (localStorage.dobDate) {
this.form.dobDate = localStorage.dobDate;
}
if (localStorage.dobMonth) {
this.form.dobMonth = localStorage.dobMonth;
}
if (localStorage.dobYear) {
this.form.dobYear = localStorage.dobYear;
}
},
watch: {
"form.dobDate": {
handler: function(after, before) {
localStorage.dobDate = after;
},
deep: true
},
"form.dobMonth": {
handler: function(after, before) {
localStorage.dobMonth = after;
},
deep: true
},
"form.dobYear": {
handler: function(after, before) {
localStorage.dobYear = after;
},
deep: true
}
请问您会发现它会变得非常重复,例如,如果我的表格很大,并且我不想在每个字段中都这样做。有什么办法可以使它变得更干吗?例如,是否可以通过某种方式使表单中的任何字段更具动态性?
答案 0 :(得分:3)
在已挂接的挂钩中,创建一个localStorage字段[“ dobDate”,“ dobMonth”,“ dobYear”]的数组,并使用forEach
方法遍历该字段,对于每个字段localStorage[fieldName]
,检查是否已定义使用conditional operator
,如果已定义,则将其分配给form
数据属性中的对应字段名称,否则传递到下一个元素:
mounted(){
["dobDate","dobMonth","dobYear"].forEach(field=>{
localStorage[field]?this.form[field]=localStorage[field]:{};
})
}
在watch
属性中,深入观察form
对象(观察其嵌套字段),然后通过执行已安装的钩子中的倒数操作来遍历其键:
watch: {
form: {
handler: function(after, before) {
Object.keys(after).forEach(key=>{
localStorage[key]=after[key]
})
},
deep: true
}
}
答案 1 :(得分:2)
这是具有多个(无深度)观察者的另一种方法。
data: {
form: {},
dateFields: ['dobDate', 'dobMonth', 'dobYear']
},
mounted() {
for (const dateField of this.dateFields) {
if (localStorage[dateField])
this.$set(this.form, dateField, localStorage[dateField])
}
},
created() {
for (const dateField of this.dateFields) {
this.$watch('form.' + dateField, function(after, before) {
localStorage[dateField] = after;
});
}
}
我忽略了它是否比仅一个深度监视者有效或高或低。这可能取决于您的数据更改方式。
答案 2 :(得分:1)
我确定您必须有理由使用localStorage将表单数据保存在localStorage中,因此使用此代码,您可以将整个表单对象传递给localStorage并可以进行检索。在这种情况下,任何形式上的更改都会使该手表运行
mounted() {
if (localStorage.form) {
this.form = localStorage.form
}
},
watch: {
"form": {
handler: function(after, before) {
localStorage.form = after;
},
deep: true
}
}