我正在使用事件总线将数据从一个组件(单击时)传递到使用事件总线(同级组件)的另一个组件。当我单击服务器组件中的“服务器”时,它将数据(服务器状态)发送到服务器详细信息组件。此数据替换服务器详细信息组件中屏幕上的默认消息。问题是服务器状态仅显示几分之一秒,然后变回默认消息。似乎每次从事件总线接收到数据时都会刷新页面。
main.js:
import Vue from 'vue'
import App from './App.vue'
export const eventBus = new Vue();
new Vue({
el: '#app',
render: h => h(App)
})
应用程序.vue:
<template>
<div class="container">
<app-header></app-header>
<hr>
<div class="row">
<servers></servers>
<app-server-details></app-server-details>
</div>
<hr>
<app-footer></app-footer>
</div>
</template>
<script>
import Header from './components/Shared/Header.vue';
import Footer from './components/Shared/Footer.vue';
import Servers from './components/Server/Servers.vue';
import ServerDetails from './components/Server/ServerDetails.vue';
export default {
components: {
appHeader: Header,
Servers,
'app-server-details': ServerDetails,
'app-footer': Footer
}
}
</script>
<style>
</style>
服务器.vue:
<template lang="pug">
div.col-xs-12.col-sm-6
ul.list-group
a(href="" v-for="server in servers" @click="exportStatus(server.id)")
li.list-group-item Server \#{{ server.id }}
</template>
<script>
import {eventBus} from '../../main'
export default {
data: function() {
return {
servers: [
{id: 1, status: 'Normal'},
{id: 2, status: 'Critical'},
{id: 3, status: 'Normal'},
{id: 4, status: 'Unknown'},
{id: 5, status: 'Down'},
]
}
},
methods: {
exportStatus(id) {
this.status = this.servers[id -1];
eventBus.$emit('statusUpdate', this.status);
}
}
}
</script>
<style scoped>
a {
text-decoration: none;
color: #333;
}
.list-group-item:hover {
color: #fff;
background-color: #777;
}
</style>
服务器详细信息.vue:
<template lang="pug">
div.col-xs-12.col-sm-6
p {{status}}
</template>
<script>
import {eventBus} from '../../main'
export default {
data: function() {
return {
status: 'Server Details are currently not updated'
}
},
created() {
eventBus.$on('statusUpdate', (data) => {
this.status = data;
});
}
}
</script>
<style>
</style>
最佳答案
您的页面已刷新,因为您的链接具有 href=""
。删除它,它就不会回发。或者使用不同的标签并使其可点击。
例如,您可以将点击处理程序(和 v-for
)添加到您的 li
中。
关于javascript - 从事件总线接收到事件后,VueJS 页面刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44165446/