使用vue-tv-focusable插件来实现焦点移动
注意: 进入页面时想让某个元素聚焦,要在 nextTick 回调中进行,否则会因页面未加载完全而导致焦点移动并不如你所愿。
<div class="item" ref="myDiv">s</div>
export default class Example1 extends Vue {
created() {
this.$nextTick(() => {
this.$tv.requestFocus(this.$refs.myDiv)
})
}
}
知识点:如何获取通过v-for遍历出来的组件或元素的dom
在vue3中不能直接用ref来获取全部节点的数组,需要通过ref函数
1、声明一个空数组用来存放遍历出来的所有dom
let channelBtnRef: any[] = [] }
2、为遍历组件绑定ref函数
<channel-btn :btnInfo="item" :ref="setChannelBtnRef"></channel-btn>
3、把获取到的dom放到channelBtnRef数组中
channelBtnRef.push(el)
4、为channelBtnRef数组下标为0的元素(全屏按钮),添加焦点
proxy.$tv.requestFocus(channelBtnRef[0])
完整代码
import { getCurrentInstance } from 'vue'
setup() {
const { proxy } = getCurrentInstance() as any
let channelBtnRef: any[] = []
const setChannelBtnRef = (el: any) => {
if (el) {
channelBtnRef.push(el)
}
}
onMounted(() => {
nextTick(() => {
proxy.$tv.requestFocus(channelBtnRef[0])
})
})
return { channelBtnData, setChannelBtnRef }
}