Vue 인스턴스 메서드 내에 확산된 mapMutations에서 "this"를 사용할 수 있습니까?
Vuex 돌연변이를 다음과 같이 설정하려고 합니다.
export default {
props: {
store: String
},
methods: {
...mapMutations({
changeModel: `${this.store}/changeModel`
})
}
}
하지만 나는 오류를 알아챘다:
Uncaughed TypeError: 정의되지 않은 속성 'store'를 읽을 수 없습니다.
모듈 변환명 안에 있는 소품을 올바르게 사용하려면 어떻게 해야 하나요?
지도를 만들고 싶다this.$store.commit('form1/changeModel')
,어디에form1
소품으로 세팅되어 있습니다.
Vuex 도우미mapMutations
와 연동하는 기능과 함께 사용할 수 있다this
.
이에 대한 문서는 없는 것 같습니다만, Vuex 유닛의 test helpers.spec.js 는 패턴을 나타내고 있습니다.
const vm = new Vue({
store,
methods: mapMutations({
plus (commit, amount) {
commit('inc', amount + 1)
}
})
})
보너스로, 이 함수는 일반적인 요건인 변이에 파라미터를 전달할 수 있습니다.
코드 변경은 다음과 같습니다.
export default {
props: {
store: String
},
methods: {
...mapMutations({
changeModel(commit) { commit(`${this.store}/changeModel`) }
})
}
}
컴포넌트 내에서의 콜은changeModel()
- map Mutations는 그 주사기를commit
파라미터를 지정합니다.
주의: 이것은 약간의 노이즈(심플한 것에 비해)를 제외하고, 많은 것을 추가할 수 있는지는 잘 모르겠습니다.this.$store.commit()
). 단, 당신의 요건은 예시 코드보다 더 복잡할 수 있습니다.
mapActions에서는 바인드 할 수 없다고 생각합니다.하지만 당신은 다음과 같이 부를 수 있다.$store.dispatch
methods: {
changeModel() {
this.$store.dispatch(`${this.store}/changeModel`);
}
}
당신이 요청한 해결책은 아니지만 효과는 동일합니다.변이는 가변 파라미터이므로 변이명을 변경하는 대신 입력 파라미터로서 함수에 넣는 것이 당연하다.스토어에서 다음과 같은 액션을 만듭니다.
changeModel ({dispatch, commit, rootGetters}, mutationName) {
commit(`${mutationName}/changeModel`, {}, {root: true})
})
mutationName을 전달하는 컴포넌트에서 이 액션을 사용합니다.
언급URL : https://stackoverflow.com/questions/52085190/can-i-use-this-in-mapmutations-spread-inside-vue-instance-methods
'programing' 카테고리의 다른 글
Vuex - http 서버에서 스토어 데이터를 로드/초기화하는 시기 (0) | 2022.08.23 |
---|---|
[Vue warn] :상위 구성 요소가 다시 렌더링될 때마다 값이 덮어쓰기되므로 프로펠을 직접 변환하지 마십시오. (0) | 2022.08.23 |
루프 또는 조건 없이 1~1000 인쇄 (0) | 2022.08.23 |
Javadoc 태그가 완전하지 않은 경우 Maven은 Java 8에서 작동하지 않습니다. (0) | 2022.08.23 |
C의 3진수(조건부) 연산자 (0) | 2022.08.23 |