vue.js - 从 App.vue 发出事件并在组件中捕获
问题描述
我正在尝试在 Vue 中实现注销处理。我重定向到主页,它在所有页面上都可以正常工作,除了主页没有刷新。所以我决定在捕捉到它后发出一个信号并刷新数据。
应用程序.vue
<b-dropdown-item href="#0" v-on:click="signMeOut()">Sign out</b-dropdown-item>
methods: {
signMeOut() {
this.$store.dispatch('SIGN_USER_OUT');
if (this.$route.path === '/') {
this.$emit('sign-out');
} else {
this.$router.push({ name: 'home' });
}
},
主页.vue
<b-container fluid="true" class="pt-3 w-75 m-auto" v-on:sign-out="reload">
created() {
this.$store.dispatch('INIT_STREAM');
},
methods: {
reload() {
console.log('reload');
this.$store.dispatch('INIT_STREAM');
},
},
但信号没有到达 Home.vue 或被忽略。我该如何解决?或者您对此退出程序有更好的解决方案吗?
解决方案
当你使用钩子时$emit
。
$root
你应该从你的 vuejs 应用程序中监听这个事件, $root
. 因此,为了达到预期的结果,您只需将代码更改为:
在您的组件home
中(我只放置script
.vue 文件中的会话)
<script>
export default {
name: 'Home',
components: {
HelloWorld
},
created(){
this.$root.$once('mylogouthandler', this.logoutEventHandler)
},
methods: {
logoutEventHandler() {
console.log('exit')
//do your stuff here.
}
}
}
</script>
带有操作注销的组件。
<template>
<div class="about">
<button @click="handleButtonClick()">logout</button>
</div>
</template>
<script>
export default {
name: 'About',
methods: {
handleButtonClick(){
console.log('clicked')
this.$root.$emit('mylogouthandler')
}
}
}
</script>
如果你想了解更多,这里是在 vuejs 中处理事件的文档。
推荐阅读
- docker - 在 MacOS 上禁用 dotnet/docker 的 SSL 要求
- annotations - 使用 Postman 的 D365 机会备注附件
- python - 具有多个索引的 Pandas 数据透视表排序
- javascript - 如何使用动态生成的属性名称访问表单属性以填充多个下拉列表
- c# - 如何在 xamarin.forms 中为 collectionview 中的元素设置动画
- css - 前两个单元格的动态 CSS 网格
- python - 在 Tree View Odoo 14 中禁用可编辑字段
- html - 如何在角度原生脚本上反转换行布局的顺序
- sql - 未能在 redshift 中对特定模式的表授予选择权限
- xamarin.forms - 为什么 Syncfusion Xamarin.Forms DataForm 忽略列跨度的网格附加属性?