반응형
Vue.js 2에서 이벤트 버스를 사용하여 사용자 지정 이벤트로 데이터를 전달하는 방법
나는 Vue.js 2.5.x를 사용하고 있다.
내 장난감 프로젝트에서 나는 이벤트 버스를 구현했다(여기 보이는 것과 유사함).이벤트 버스는 Vue 프로토타입에 다음과 같이 전역적으로 등록되어 있음$eventBus
.
그리고 다음과 같은 이벤트를 발생시키는 요소를 만들었다.
this.$eventBus.$emit('actionCompleted')
그리고 그 자체의 기능을 실행하기 위해 그 사건에 등록하는 또 다른 것.myMethod
), 아래와 같이
export default {
created: function () {
this.$eventBus.$on('actionCompleted', this.myMethod)
},
methods: {
myMethod () {
console.log('myMethod called')
}
}
}
지금까지는 모든 것이 예상대로 잘 된다.
문제는 어떻게 하면 수신자에게 추가 정보를 보낼 수 있도록 개체를 사용자 지정 이벤트에 전달할 수 있는가입니다.
매개 변수를 두 번째 인수로 전달할 수 있음
this.$eventBus.$emit('actionCompleted', objectParams)
export default {
created: function () {
this.$eventBus.$on('actionCompleted', this.myMethod)
},
methods: {
myMethod (objectParams) {
console.log('myMethod called', objectParams)
}
}
}
다음 튜토리얼을 확인하십시오.
단일 인수에 대해 다음과 같은 이벤트를 만들 수 있다.
this.$eventBus.$emit('actionCompleted',args)
쉼표로 분리된 값으로 다중 인수를 전달할 수 있다.
다중 인수:
this.$eventBus.$emit('actionCompleted',args1, args2 ...)
그러한 주장을 통과하면 다음과 같이 [단일 논쟁에 대해]을 얻을 수 있다.
export default {
created: function () {
this.$eventBus.$on('actionCompleted', this.myMethod)
},
methods: {
myMethod (args) {
console.log('myMethod called', args)
}
}
}
이벤트 버스를 통해 간단하게 물체를 방출할 수 있다.
this.$eventBus.$emit('actionCompleted', this.yourObject)
그리고 이렇게 잡는다.
export default {
created: function () {
this.$eventBus.$on('actionCompleted', this.myMethod)
},
methods: {
myMethod (objectParams) {
console.log('myMethod called', objectParams)
}
}
}
반응형
'programing' 카테고리의 다른 글
MVC 프로젝트에서 MapState가 Vue3와 함께 Vuex4를 찾을 수 없음 (0) | 2022.05.15 |
---|---|
Vuex를 사용하는 글로벌 이벤트 버스 - 항상 가입자에게 알림 (0) | 2022.05.15 |
LocalDate를 문자열로 포맷하는 방법? (0) | 2022.05.14 |
Linux/unix에 WinAPI의 MAX_PATH와 동등한 것이 있는가? (0) | 2022.05.14 |
왜 내 부에즈 메서드는 루프를 사용하지도 않는데 무한 루프 생성 콜인가? (0) | 2022.05.14 |