【发布时间】:2021-12-07 19:42:02
【问题描述】:
我有一个键盘导航系统。当您按下 ArrowUp 或 ArrowDown 时,会从 app.js(我发现监听这些按键的最佳位置,因为它们需要在系统范围内)向组件中的 mount() 发出一个事件。
组件的mounted() 部分内的Event.$on() 然后调用一个函数,该函数使用$refs 来识别当前选定的项目,并在按下ENTER 时显示它是模态的。
app.js 代码(监听按键):
else if (event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'Enter') {
event.preventDefault()
switch (this.$router.currentRoute.path) {
case "/pedidos":
Event.$emit('navegarSetasPedidos', event.key)
break;
case "/clientes":
Event.$emit('navegarSetasClientes', event.key)
break;
}
}
相关组件的mounted() 部分:
mounted() {
Event.$on('navegarSetasPedidos', (key) => {this.navegarSetas(key)})
}
负责导航的函数(抱歉格式错误,还没有弄清楚stackoverflow的代码块是如何工作的):
navegarSetas(key) {
if (this.navegacaoSetasAtiva == false) {
this.navegacaoSetasAtiva = true
this.navegacaoAtual = 0
} else if (this.modalAtivado == false && this.navegacaoSetasAtiva == true) {
if (key == 'ArrowDown' && this.navegacaoAtual < this.pedidos.length - 1) {
this.navegacaoAtual++
let elementoSelecionado = this.$refs['pedido'+this.navegacaoAtual][0].$el
let boundaries = elementoSelecionado.getBoundingClientRect()
if (boundaries.top < 0 || boundaries.top > (window.innerHeight || document.documentElement.clientHeight)){
elementoSelecionado.scrollIntoView({behavior: 'smooth'})
}
} else if (key == 'ArrowUp' && this.navegacaoAtual <= this.pedidos.length && this.navegacaoAtual > 0) {
this.navegacaoAtual--
let elementoSelecionado = this.$refs['pedido'+this.navegacaoAtual][0].$el
let boundaries = elementoSelecionado.getBoundingClientRect()
if (boundaries.top < 0 || boundaries.top > (window.innerHeight || document.documentElement.clientHeight)){
elementoSelecionado.scrollIntoView({behavior: 'smooth'})
}
} else if (key == 'Enter') {
let pedidoSelecionado = this.pedidos[this.navegacaoAtual].id
Event.$emit('changeShow', pedidoSelecionado)
}
}
第一次访问时效果很好。问题是,如果我更改当前路线以显示另一个组件然后返回到前一个组件,我会得到很多“this.$refs['pedido'+this.navegacaoAtual][0].$el is undefined”错误,但系统仍然可以正常工作,尽管不正常。
有趣的是:如果我控制台日志“this.$refs['pedido'+this.navegacaoAtual][0].$el is undefined”,我会在错误之前得到一个 EMPTY 日志,然后是另一个这次就在它的正下方,不是空的。
我搜索过的所有其他地方都说问题出在 Vue 如何重新渲染事物,并且我在渲染之前调用了这个事件,这不应该是不可能的,因为我在内部调用它()。
非常感谢任何帮助,谢谢!
【问题讨论】:
标签: vuejs2 vue-router