element-ui Carousel 走馬燈源碼分析整理筆記(十一)

来源:https://www.cnblogs.com/fangnianqin/archive/2018/12/13/10115069.html
-Advertisement-
Play Games

Carousel 走馬燈源碼分析整理筆記,這篇寫的不詳細,後面有空補充 main.vue item.vue ...


Carousel 走馬燈源碼分析整理筆記,這篇寫的不詳細,後面有空補充

main.vue

<template>
  <!--走馬燈的最外層包裹div-->
  <div class="el-carousel"
    :class="{ 'el-carousel--card': type === 'card' }"
    @mouseenter.stop="handleMouseEnter"
    @mouseleave.stop="handleMouseLeave">
    <div class="el-carousel__container" :style="{ height: height }">
      <!--左邊的切換箭頭-->
      <transition name="carousel-arrow-left">
        <button
          type="button"
          v-if="arrow !== 'never'"
          v-show="(arrow === 'always' || hover) && (loop || activeIndex > 0)"
          @mouseenter="handleButtonEnter('left')"
          @mouseleave="handleButtonLeave"
          @click.stop="throttledArrowClick(activeIndex - 1)"
          class="el-carousel__arrow el-carousel__arrow--left">
          <i class="el-icon-arrow-left"></i>
        </button>
      </transition>
      <!--右邊的切換箭頭-->
      <transition name="carousel-arrow-right">
        <button
          type="button"
          v-if="arrow !== 'never'"
          v-show="(arrow === 'always' || hover) && (loop || activeIndex < items.length - 1)"
          @mouseenter="handleButtonEnter('right')"
          @mouseleave="handleButtonLeave"
          @click.stop="throttledArrowClick(activeIndex + 1)"
          class="el-carousel__arrow el-carousel__arrow--right">
          <i class="el-icon-arrow-right"></i>
        </button>
      </transition>
        <!--幻燈片內容顯示區域-->
      <slot></slot>
    </div>
    <!--底部的指示器列表,點擊或hover時切換幻燈片-->
    <ul
      class="el-carousel__indicators"
      v-if="indicatorPosition !== 'none'"
      :class="{ 'el-carousel__indicators--labels': hasLabel, 'el-carousel__indicators--outside': indicatorPosition === 'outside' || type === 'card' }">
      <li
        v-for="(item, index) in items"
        class="el-carousel__indicator"
        :class="{ 'is-active': index === activeIndex }"
        @mouseenter="throttledIndicatorHover(index)"
        @click.stop="handleIndicatorClick(index)">
        <button class="el-carousel__button"><span v-if="hasLabel">{{ item.label }}</span></button>
      </li>
    </ul>

  </div>
</template>

<script>
 //throttle節流函數
import throttle from 'throttle-debounce/throttle';
import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event';

export default {
  name: 'ElCarousel',

  props: {
    initialIndex: { //初始狀態激活的幻燈片的索引,從 0 開始
      type: Number,
      default: 0
    },
    height: String, //走馬燈的高度
    trigger: { //指示器的觸發方式
      type: String,
      default: 'hover'
    },
    autoplay: { //是否自動切換
      type: Boolean,
      default: true
    },
    interval: { //自動切換的時間間隔,單位為毫秒
      type: Number,
      default: 3000
    },
    indicatorPosition: String, //指示器的位置
    indicator: {
      type: Boolean,
      default: true
    },
    arrow: {  //切換箭頭的顯示時機 always/hover/never
      type: String,
      default: 'hover'
    },
    type: String, //走馬燈的類型,card
    loop: {  //是否迴圈顯示
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      items: [],  //幻燈片數組
      activeIndex: -1, //標識當前幻燈片索引
      containerWidth: 0,
      timer: null,
      hover: false //記錄當前滑鼠的移入狀態
    };
  },

  computed: {
    hasLabel() {
      return this.items.some(item => item.label.toString().length > 0);
    }
  },

  watch: {
    items(val) {
      if (val.length > 0) this.setActiveItem(this.initialIndex);
    },

    activeIndex(val, oldVal) {
      this.resetItemPosition(oldVal);
      this.$emit('change', val, oldVal);
    },

    autoplay(val) {
      val ? this.startTimer() : this.pauseTimer();
    },

    loop() {
      this.setActiveItem(this.activeIndex);
    }
  },

  methods: {
    // 當滑鼠移入
    handleMouseEnter() {
      // 當滑鼠移入時,清空幻燈片播放的定時器,暫停自動切換。
      this.hover = true;
      this.pauseTimer();
    },
    // 當滑鼠移出
    handleMouseLeave() {
      //  當滑鼠移出,設置幻燈片自動播放定時器
      this.hover = false;
      this.startTimer();
    },

    itemInStage(item, index) {
      const length = this.items.length;
      // 滿足當前為最後一個幻燈片;當前幻燈片在場景內;第一個幻燈片激活狀態;
      //  或者 滿足 當前幻燈片在場景內;當前幻燈片後面有至少一個項目;當前幻燈片後面一個項目處於激活狀態
      if (index === length - 1 && item.inStage && this.items[0].active ||
        (item.inStage && this.items[index + 1] && this.items[index + 1].active)) {
        return 'left';
      } else if (index === 0 && item.inStage && this.items[length - 1].active ||
        (item.inStage && this.items[index - 1] && this.items[index - 1].active)) {
        return 'right';
      }
      return false;
    },
    // 當滑鼠移入左邊的切換幻燈片的按鈕
    handleButtonEnter(arrow) {
      this.items.forEach((item, index) => {
        if (arrow === this.itemInStage(item, index)) {
          item.hover = true;
        }
      });
    },

    handleButtonLeave() {
      this.items.forEach(item => {
        item.hover = false;
      });
    },
    // 將所有的幻燈片放入items數組中
    updateItems() {
      this.items = this.$children.filter(child => child.$options.name === 'ElCarouselItem');
    },
    //  重置幻燈片位置
    resetItemPosition(oldIndex) {
      this.items.forEach((item, index) => {
        item.translateItem(index, this.activeIndex, oldIndex);
      });
    },
    //改變當前的幻燈片
    playSlides() {
      if (this.activeIndex < this.items.length - 1) {
        this.activeIndex++;
      } else if (this.loop) {
        this.activeIndex = 0;
      }
    },

    pauseTimer() {
      // 清空定時器
      clearInterval(this.timer);
    },

    startTimer() {
      //  如果自動切換的時間間隔小於等於0時,或者用戶未設置自動播放時,直接返回,幻燈片不自動播放
      if (this.interval <= 0 || !this.autoplay) return;
      this.timer = setInterval(this.playSlides, this.interval);
    },
    //設置當前頁
    setActiveItem(index) {
      // 如果index是字元串,則是用戶設置了幻燈片的name
      if (typeof index === 'string') {
        // 找到對應name的幻燈片
        const filteredItems = this.items.filter(item => item.name === index);
        // 如果找到的items長度大於0,取第一個的索引作為我們要使用的索引
        if (filteredItems.length > 0) {
          index = this.items.indexOf(filteredItems[0]);
        }
      }
      // 索引轉成數字
      index = Number(index);
      // 如果索引不是數字,或者不是整數
      if (isNaN(index) || index !== Math.floor(index)) {
        // 如果不是生產環境下,就報warn
        process.env.NODE_ENV !== 'production' &&
        console.warn('[Element Warn][Carousel]index must be an integer.');
        return;
      }
      // 獲取幻燈片數組的長度
      let length = this.items.length;
      const oldIndex = this.activeIndex;
      // 如果索引小於0,判斷是否設置迴圈播放,如果設置了,設置當前頁為最後一頁;也就是在向前切換到第一張,繼續向前切換顯示最後一張,然後顯示倒數第二張
      if (index < 0) {
        this.activeIndex = this.loop ? length - 1 : 0;
      } else if (index >= length) { //如果索引大於數組長度,判斷是否設置迴圈播放,如果設置了,設置當前頁為第一頁;也就是在向後切換到最後一張時,繼續向後切換顯示第一張,然後顯示第二張
        this.activeIndex = this.loop ? 0 : length - 1;
      } else { //否則,當前頁設置為索引頁
        this.activeIndex = index;
      }

      if (oldIndex === this.activeIndex) {
        this.resetItemPosition(oldIndex);
      }
    },

    prev() {
      this.setActiveItem(this.activeIndex - 1);
    },

    next() {
      this.setActiveItem(this.activeIndex + 1);
    },

    handleIndicatorClick(index) {
      this.activeIndex = index;
    },

    handleIndicatorHover(index) {
      if (this.trigger === 'hover' && index !== this.activeIndex) {
        this.activeIndex = index;
      }
    }
  },

  created() {
    // throttle節流函數,點擊頻率控制,返回函數連續調用時   http://npm.taobao.org/package/throttle-debounce
    // 第二個參數noTrailing,當其設置為true時,保證函數每隔delay時間只能執行一次,如果設置為false或者沒有指定,則會在最後一次函數調用後的delay時間後重置計時器。
    this.throttledArrowClick = throttle(300, true, index => {
      this.setActiveItem(index);
    });
    this.throttledIndicatorHover = throttle(300, index => {
      this.handleIndicatorHover(index);
    });
  },

  mounted() {
    this.updateItems();
    this.$nextTick(() => {
      addResizeListener(this.$el, this.resetItemPosition);
      if (this.initialIndex < this.items.length && this.initialIndex >= 0) {
        this.activeIndex = this.initialIndex;
      }
      this.startTimer();
    });
  },

  beforeDestroy() {
    if (this.$el) removeResizeListener(this.$el, this.resetItemPosition);
  }
};
</script>

item.vue

<template>
  <!--單個的幻燈片html結構-->
  <div v-show="ready" class="el-carousel__item"
    :class="{
      'is-active': active,
      'el-carousel__item--card': $parent.type === 'card',
      'is-in-stage': inStage,
      'is-hover': hover,
      'is-animating': animating
    }"
    @click="handleItemClick"
    :style="{
      msTransform: `translateX(${ translate }px) scale(${ scale })`,
      webkitTransform: `translateX(${ translate }px) scale(${ scale })`,
      transform: `translateX(${ translate }px) scale(${ scale })`
    }">
    <div v-if="$parent.type === 'card'" v-show="!active" class="el-carousel__mask"></div>
    <!--幻燈片的自定義內容以插槽的方式顯示在此區域-->
    <slot></slot>
  </div>
</template>

<script>
  const CARD_SCALE = 0.83;
  export default {
    name: 'ElCarouselItem',

    props: {
      name: String, //幻燈片的名字,可用作 setActiveItem 的參數
      label: { //該幻燈片所對應指示器的文本
        type: [String, Number],
        default: ''
      }
    },

    data() {
      return {
        hover: false,
        translate: 0, //偏移量設置
        scale: 1,
        active: false,
        ready: false,
        inStage: false,
        animating: false
      };
    },

    methods: {
      processIndex(index, activeIndex, length) {
        if (activeIndex === 0 && index === length - 1) {
            //當前是activeIndex是第一張,index是最後一張,返回-1,相差-1,表示二者相鄰且在左側
          return -1;
        } else if (activeIndex === length - 1 && index === 0) {
          //當前頁activeIndex是最後一張,index是第一張,返回length,相差1,表示二者相鄰且在右側
          return length;
        } else if (index < activeIndex - 1 && activeIndex - index >= length / 2) {
            // 如果,index在activeIndex前一頁的前面,並且之間的間隔在一半頁數即以上,則返回頁數長度+1,這樣它們會被置於最右側
          return length + 1;
        } else if (index > activeIndex + 1 && index - activeIndex >= length / 2) {
            // 如果,index在activeIndex後一頁的後面,並且之間的間隔在一般頁數即以上,則返回-2,這樣它們會被置於最左側
          return -2;
        }
        return index;
      },

      calculateTranslate(index, activeIndex, parentWidth) {
        if (this.inStage) {
          return parentWidth * ((2 - CARD_SCALE) * (index - activeIndex) + 1) / 4;
        } else if (index < activeIndex) {
          return -(1 + CARD_SCALE) * parentWidth / 4;
        } else {
          return (3 + CARD_SCALE) * parentWidth / 4;
        }
      },
      // 這是用來移動幻燈片。
      translateItem(index, activeIndex, oldIndex) {
        // 獲取父組件的寬度
        const parentWidth = this.$parent.$el.offsetWidth;
        // 獲取幻燈片數組的長度
        const length = this.$parent.items.length;
        // 如果不是card模式
        if (this.$parent.type !== 'card' && oldIndex !== undefined) {
          this.animating = index === activeIndex || index === oldIndex;
        }
        if (index !== activeIndex && length > 2 && this.$parent.loop) {
          // 對當前索引進行處理
          index = this.processIndex(index, activeIndex, length);
        }
        if (this.$parent.type === 'card') {
          this.inStage = Math.round(Math.abs(index - activeIndex)) <= 1;
          this.active = index === activeIndex;
          this.translate = this.calculateTranslate(index, activeIndex, parentWidth);
          this.scale = this.active ? 1 : CARD_SCALE;
        } else {
          this.active = index === activeIndex;
          // 設置幻燈片的偏移量
          this.translate = parentWidth * (index - activeIndex);
        }
        this.ready = true;
      },

      handleItemClick() {
        const parent = this.$parent;
        if (parent && parent.type === 'card') {
          const index = parent.items.indexOf(this);
          parent.setActiveItem(index);
        }
      }
    },

    created() {
      this.$parent && this.$parent.updateItems();
    },

    destroyed() {
      this.$parent && this.$parent.updateItems();
    }
  };
</script>

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 我們經常將數據存儲在XML 中,在展示的時候需要轉換為其它的形式,這裡介紹使用XSLT 對XML數據進行轉換。 要學習XSLT對XML的轉換,需要先瞭解三個文件。 第一個是存儲數據的XML文件:employees.xml 第二個是存儲XSLT的文件:employees.xslt 第三個是我們進行轉換 ...
  • 聲明 本篇內容摘抄自以下兩個來源: "BootStrap中文網" 感謝大佬們的分享。 正文 響應式佈局(BootStrap) 這次想來講講一個前端開發框架:BootStrap BootStrap 目前已經出了 4 個版本,每個版本都有對應的官網教程,先來看看不同版本里的宣傳語: 簡潔、直觀、強悍的前 ...
  • 概念 Webpack是一個模塊打包機,它可以將我們項目中的所有js、圖片、css等資源,根據其入口文件的依賴關係,打包成一個能被瀏覽器識別的js文件。能夠幫助前端開發將打包的過程更智能化和自動化。 WebPack和Grunt以及Gulp相比有什麼特性 WebPack和Grunt以及Gulp相比有什麼 ...
  • 一、關於選擇器的命名 W3C CSS2.1的 4.1.3 節中提到:標識符(包括選擇器中的元素名,類和ID)只能包含字元[a- zA-Z0-9]和ISO 10646字元編碼U+00A1及以上,再加連字型大小(-)和下劃線(_);它們不能以 數字,或一個連字型大小後跟數字為開頭。它們還可以包含轉義字元加任何I ...
  • 今天工作中使用了這個,感覺很好用啊! 首先: 這個ReactDom是幹嘛用的? 答: react-dom 包提供了 DOM 特定的方法,可以在你的應用程式的頂層使用,如果你需要的話,也可以作為 React模型 之外的特殊操作DOM的介面。 但大多數組件應該不需要使用這個模塊。 其次: 如何引用? 答 ...
  • 首先我們先來林格斯雙擊翻譯一下: split 劈開, 使分裂; splice 接合; 使結合; slice 切成薄片, 切; 我先是這麼區分的:這三個方法最後一個字母是t的是字元串方法,是e的則是數組方法(當然字元串也有slice方法)。 split 是將字元串用符號分割。返回數組。 參數一:指定字 ...
  • 本文主要介紹了vue-router相關基礎知識及單頁面應用的工作原理,寫的十分的全面細緻,具有一定的參考價值,對此有需要的朋友可以參考學習下。如有不足之處,歡迎批評指正。 單頁面工作原理是通過瀏覽器URL的#後面的hash變化就會引起頁面變化的特性來把頁面分成不同的小模塊,然後通過修改hash來讓頁 ...
  • 移動端的項目經常會引入手勢庫來實現拖拽 不過如果只是一兩個頁面用到拖拽,再引入一個手勢庫就很不划算 最近的項目中就有這麼一個需求: 因為就這一個地方需要拖拽,所以我就沒有引入第三方庫 移動端的拖拽有兩種主流的實現方案: 1. 將元素設置為固定定位,然後在拖拽的時候修改其定位,實現拖拽的效果; 這種 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...