我正在我的 vuejs 前端的 ASP.NET Core 中实现 SignalR。为此,我需要一个全局变量来访问组件中的这些事件,但由于某种原因,dashboardHub 变量在控制台中显示为未定义。我是否在我的 vue 实例上错误地声明了它们?
<script>//setup routing using SPA VUE interface
Vue.use(VueRouter);
const routes = [
{ path: '/', component: dashboard },
]
const router = new VueRouter({
routes, // short for `routes: routes`
})
console.log('Signalr mounted', window['signalR']); // output : Undefined
var signalR = window.signalR;
try {
this.connection = new signalR.HubConnectionBuilder()
.withUrl(window.location.origin + '/dashboardHub', {})
.withAutomaticReconnect()
.build();
console.log('Signalr Connection', connection);
} catch (error) {
console.error('SignalR error ', error)
}
// use new Vue instance as an event bus
const dashboardHub = new Vue()
// every component will use this.$questionHub to access the event bus
Vue.prototype.$dashboardHub = dashboardHub
// Forward server side SignalR events through $questionHub, where components will listen to them
connection.on('UpdateDashboard', () => {
dashboardHub.$emit('review-movement-hub')
})
var vm = new Vue({
el: '#app',
vuetify: new Vuetify({
options: {
customProperties: true
},
theme: {
themes: {
light: {
primary: '#6237A0',
secondary: '#9754CB',
alternatePrimary: '#7cb6b1',
accent: '#DEACF5',
textaccent: '#28104E',
background: '#f7f7f7',
error: '#b71c1c',
},
},
},
}),
router,
data() {
return {
flexcontainer: {
'display': 'flex'
},
flexchild: {
'min-width': '0',
'flex': '1 1 auto',
}
}
}
}).$mount('#app')
</script>
我在我的仪表板组件中使用仪表板变量如下:
created() {
console.log(this.dashboardHub)
// Listen to score changes coming from SignalR events
this.dashboardHub.$on('review-movement-hub', this.test)
},
但是在 console.log 中它返回为未定义但我确实在我的 vue 实例的声明部分定义了它,如上所示。