반응형
Vue 인스턴스의 $on 메서드가 작동하지 않습니다.
main.js 파일에 다음과 같은 이벤트버스를 만들었습니다.
main.discloss.main.discloss.
Vue.prototype.$bus = new Vue()
그 후, 다음과 같이 이벤트 버스를 테스트하기 위한 코드를 작성했습니다.
테스트 컴포넌트
<template>
<div>
<div class="account-modal_form">
<form action="" @submit.prevent="formSubmit">
<div class="account-modal_form__group" :class="{ warning: errors.has('password') }">
<div class="account-modal_form__input">
<input name="password" :type="passwordType" placeholder="" class="width-316" v-validate="'required'" v-model="password">
<i class="account-modal_form__viewpass" @click="togglePassword"></i>
</div>
<span class="account-modal_form__warning" v-show="errors.has('password')">
{{ errors.first('password') }}
</span>
</div>
{{ errors }}
<div class="account-modal_form__group">
<button type="submit" class="btn btn--primary btn--large">next</button>
<button type="button" class="btn btn--default" @click="cancelAction">cancel</button>
</div>
</form>
</div>
</div>
</template>
<script>
import { API } from '@/api'
export default {
data() {
return {
passwordType: 'password',
password: ''
}
},
methods: {
created() {
this.$bus.$on('test', () => console.log('test'));
},
nextStep() {
this.$bus.$emit('test');
},
formSubmit() {
this.nextStep();
}
}
}
</script>
[ Submit ]버튼을 클릭했을 때 먼저 폼을 송신하고 다음 단계를 호출하여 이벤트를 송신하고 싶은데 $on 이벤트는 아무것도 출력하지 않습니다.
당신은 달리고 있다$emit
전에$on
이벤트를 시작할 때 그 시점에는 청취자가 없으므로 청취자를 컴포넌트에 등록하는 것이 좋습니다.created
라이프 사이클 이벤트, 그렇지 않으면 테스트 방법을 실행할 때마다 새 청취자를 등록합니다.
Vue.prototype.$bus = new Vue();
Vue.component('spy-component', {
template: '<p>{{this.text}}</p>',
data() {
return {
text: '',
}
},
created() {
this.$bus.$on('sendOriginPassword', (text) => {
this.text = text;
});
}
})
Vue.component('test-component', {
template: '<button @click="test">Click me</button>',
created() {
this.$bus.$on('sendOriginPassword', () => {
console.log('I am listening event')
});
},
methods: {
test() {
this.$bus.$emit('sendOriginPassword', 'Can you hear me?');
}
}
});
new Vue({
el: "#app",
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<spy-component></spy-component>
<test-component></test-component>
</div>
언급URL : https://stackoverflow.com/questions/50341781/vue-instances-on-method-is-not-work
반응형
'programing' 카테고리의 다른 글
왜 기억에 쓰는 것이 읽는 것보다 훨씬 느릴까요? (0) | 2022.07.07 |
---|---|
C/C++ 메인 함수의 파라미터는 어디에 있습니까? (0) | 2022.07.07 |
리소스 속성에 ResourceBundle을 사용하여 UTF-8을 사용하는 방법 (0) | 2022.07.07 |
Joda-Time DateTime을 mm/dd/yyyy로만 포맷하는 방법 (0) | 2022.07.07 |
int를 ASCII 문자로 변환합니다. (0) | 2022.07.04 |