반응형
계산된 특성에 대한 동적 "v-model" - 경로 파라미터를 기반으로 함
나는 루트에 전달된 이름에 따라 다양한 vuex 속성을 설정하는 데 사용할 수 있는 구성 요소를 만들고 있어.이것의 순진한 요지는 다음과 같다.
<template>
<div>
<input v-model="this[$route.params.name]"/>
</div>
</template>
<script>
export default {
computed: {
foo: {
get(){ return this.$store.state.foo; },
set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
},
bar: {
get(){ return this.$store.state.bar; },
set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
},
}
}
</script>
내가 합격했다는 것을 주의하라.this[$route.params.name]
에게v-model
역동적으로 만들기 위해서.이는 설정(구성 요소 로드 양호)에 사용되지만 값을 설정하려고 할 때 다음과 같은 오류가 표시됨:
Cannot set reactive property on undefined, null, or primitive value: null
내 생각에 이것은 때문이다.this
안쪽에v-model
정의가 없어지다(?)
어떻게 하면 이 일을 해낼 수 있을까?
갱신하다
나는 또한 왜 이것이 작동하지 않는지 궁금할 것이다(컴파일 오류:
<template>
<div>
<input v-model="getComputed()"/>
</div>
</template>
<script>
export default {
computed: {
foo: {
get(){ return this.$store.state.foo; },
set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
},
bar: {
get(){ return this.$store.state.bar; },
set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
},
},
methods: {
getComputed(){
return this[this.$route.params.name]
}
}
}
</script>
네 안에 있는 모든 것<template>
에 있다this
범위, 그러니까this
정의되지 않았다.
v-model
에 대한 통사설탕일 뿐이다.:value
그리고@input
에 대한 사용자 정의 이벤트와 계산된 속성으로 이 문제를 처리할 수 있다.:value
.
계산된 속성을 getter와 setter와 함께 사용할 수도 있다.
computed: {
model: {
get: function () {
return this.$store.state[this.$route.params.name]
},
set: function (value) {
this.$store.commit('updateValue', { name: this.$route.params.name, value})
}
}
}
편집 세터 내에서 더 많은 논리를 수행할 수 있는 경우 그렇게 분리하고 단순성을 유지하면서 하나의 계산된 속성에 충실할 것이다.
computed: {
model: {
get: function () {
return this.$store.state[this.$route.params.name]
},
set: function (value) {
switch(this.$route.params.name) {
case 'foo':
return this.foo(value)
default:
return this.bar(value)
}
}
}
},
methods: {
foo(val) {
this.$store.commit(...)
},
bar(val) {
this.$store.commit(...)
}
}
반응형
'IT이야기' 카테고리의 다른 글
Vue 데이터에서 href로 값을 전달하는 방법? (0) | 2022.03.18 |
---|---|
관찰할 수 있는 약속 취소 (0) | 2022.03.18 |
왜 우리는 sys를 사용하지 말아야 하는가.py 스크립트에서 setdefaultencoding("utf-8")을 설정하시겠습니까? (0) | 2022.03.18 |
pip: 종속성을 무시한 채 강제 설치 (0) | 2022.03.18 |
URLSearchParams가 빈 객체를 반환함 (0) | 2022.03.18 |