반복 조건부 Vue.js 코드를 리팩터하려면 어떻게 해야 하나요?
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
}
예를 들어 폼이 커서 모든 필드에 대해 이 작업을 수행하고 싶지 않은 경우 반복 작업이 매우 반복될 수 있습니다.좀 더 건조하게 할 수 있는 방법이 있을까요?예를 들어 폼의 모든 필드에 대해 보다 역동적으로 만들 수 있는 방법이 있습니까?
마운트된 후크에서 localStorage 필드 ["dobDate","dobMonth","dobYear"]의 배열을 만들고 다음 명령을 사용하여 루프합니다.forEach
메서드, 각 필드의localStorage[fieldName]
를 사용하여 정의되어 있는지 확인하고 정의되어 있는 경우 에서 대응하는 필드명에 할당합니다.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
}
}
여기에서는, 복수의(심층하지 않은) 감시자를 가지는 다른 어프로치를 소개합니다.
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;
});
}
}
나는 그것이 한 명의 심층 관찰자보다 더 효율적인지 아닌지는 무시한다.데이터의 변경 방법에 따라 달라질 수 있습니다.
localStorage를 사용하여 폼 데이터를 localStorage에 저장해야 하는 이유가 있을 것입니다.이 코드를 사용하면 폼 오브젝트 전체를 localStorage에 전달하여 가져올 수 있습니다.이 경우, 어떤 형태의 변화라도 이 시계를 작동시킬 것이다
mounted() {
if (localStorage.form) {
this.form = localStorage.form
}
},
watch: {
"form": {
handler: function(after, before) {
localStorage.form = after;
},
deep: true
}
}
언급URL : https://stackoverflow.com/questions/57709947/how-can-i-refactor-repetitive-conditional-vue-js-code
'itsource' 카테고리의 다른 글
Vue 2의 클라이언트 측 검색 결과에서 aria-live 영역의 변경 내용을 제대로 읽지 않음 (0) | 2022.08.30 |
---|---|
Serializable이 무슨 뜻입니까? (0) | 2022.08.30 |
VueJS 컴포넌트 시스템 아키텍처 (0) | 2022.08.30 |
문자열에서 모든 문자 제거 (0) | 2022.08.30 |
mathjax + vue 재렌더링 방정식 (0) | 2022.08.30 |