1. 程式人生 > 實用技巧 >vue TV端焦點移動外掛-畫廊效果實現

vue TV端焦點移動外掛-畫廊效果實現

vue TV端焦點移動外掛

npm:https://www.npmjs.com/package/vue-tv-focusable
文件:https://blog.csdn.net/sllailcp/article/details/109044265

安裝

npm i -S vue-tv-focusable

main.js中

import Vue from "vue";
import focusable from 'vue-tv-focusable';
Vue.use(focusable);

tv.component.vue元件中的html(css有點多,此處就不寫了):

<div class="tv-box">
    <div class="item-box">
      <div class="perspective">
        <div class="item" v-focusable v-for="(item,index) of list" :key="index"
        @left="left(index,$event)" @right="right(index,$event)" @down="nofocus" @up="nofocus"  @click="skip(index)"
		:style="{
          left: -100 * index - index * 20 +'px',
          zIndex: activeIndex === index ? 1100 :1000-Math.abs(activeIndex - index) * 5,
          transform: `rotateY(${activeIndex < index ? '-30deg':activeIndex === index?'0deg':'30deg'}) scale(${1-Math.abs(activeIndex - index)*0.05})`,
        }">
          <img :src="item.url"/>
        </div>
      </div>
    </div>
  </div>

tv.component.vue元件中的js

  created() {
     this.$nextTick(() => {
      this.$tv.init({ distanceToCenter:true }); // 焦點居中
      this.$tv.setScrollEl(document.querySelector('.item-box')); // 設定滾動的div
      this.$tv.requestFocus(this.$tv.getElementByPath("//div[@class='perspective']/div[3]"));// 初始化第3個div聚焦
    })
  },
  destroyed() {
  // 元件銷燬,重置distanceToCenter的預設值,預設:false
    this.$tv.init({ distanceToCenter:false });
  },
  methods:{
    skip(id){ // 按ok鍵跳轉到詳情頁面
      this.loadingShow = true;
      this.$router.push({"path":"/detail",query:{id}})
    },
    nofocus(event){ this.$tv.requestFocus(event.target); },
    right(index, event){
      if(index === this.list.length - 1 ){return;}
      this.activeIndex = index + 1;
    },
    left(index,event){
      if(index === 0 ){return;}
      this.activeIndex = index - 1;
    }
 }

解釋:
1.指令v-focusable設定可獲取焦點的div
2.新增自定義事件@left,@right,按左右按鍵來計算當前層級以及縮放比例
3.新增自定義事件@up,@down,按上下按鍵的時候阻止焦點跳動
4.新增click事件,按ok鍵盤的時候跳轉詳情頁

demo地址:https://github.com/slailcp/tv-focusable-example/blob/master/vue-tv-focusable-example/src/views/example8.vue

最終介面: