自定義Weex組件——Weex的學習之路(八)

在四月份和五月份的時候我用業餘時間來學習weex,在這期間一直在看文檔寫demo,每一個組件都自己寫demo運行一遍。我本人是做Android開發的,對JS,CSS和Html有一定的瞭解,所以學習weex不是很難。然後我把自己所學的主要經歷和過程用博客記錄下來,其目的是想鞏固自己的學習知識,還有就是希望能給weex學習的小夥伴一點幫助。最近有一部分小夥伴私信我說,問我weex好學嗎、weex學了之後有用嗎、weex現在是不是沒有人維護了,還有weex和flutter哪個更好?針對這些問題,我後續會專門用一篇博客來統一回答的。不過我還是想說的就是好不好學、有沒有用,只有等你學了以後纔會知道!

到了這篇博客,我目前weex所有的組件和模塊都使用過了,那麼我發現,有一些weex原生組件最終在安卓和蘋果終端上顯示和交互的交過不一樣,有一些UI效果內置組件達不到的時候,就需要自定義組件了。自定義組件主要分爲兩大步驟:

1.重寫內置組件

前面幾篇博客寫的都是比較基礎的,那麼從這篇博客開始,複雜度就會高一些的。就拿TabPage來說吧,他原生是長這個樣子的

我們在實際項目中樣式也不定和這個相同,所以這個時候我們就需要將源碼拷貝下來,根據自己的需求改動代碼。還是以TabPage爲例,我這裏的需求是頂部的tab只有兩個,並且這兩個tab不是按權重等分的,而是相對來說比較靠近的,並且在下方還要有一條分割線。那麼我將TabPage的源碼從GitHub上拷貝下來。拷貝地址是:TabPage源碼地址

經過改動後的代碼:

<template>
  <div class="wxc-tab-page"
       :style="{ height: (tabPageHeight)+'px', backgroundColor:wrapBgColor }">
    <scroller class="tab-title-list"
              ref="tab-title-list"
              :show-scrollbar="false"
              scroll-direction="horizontal"
              :data-spm="spmC"
              :style="{
                backgroundColor: tabStyles.bgColor,
                height: (tabStyles.height)+'px',
                leftOffset:'100px',
                rightOffset: '100px'
              }">

      <div class="title-item"
           v-for="(v,index) in tabTitles"
           :key="index"
           :ref="'wxc-tab-title-'+index"
           @click="setPage(index,v.url, clickAnimation)"
           :style="{
             width: tabStyles.width +'px',
             height: tabStyles.height +'px',
             backgroundColor: currentPage === index ? tabStyles.activeBgColor : tabStyles.bgColor,
             borderBottomWidth: tabStyles.normalBottomHeight,
             borderBottomColor: tabStyles.normalBottomColor
           }"
           :accessible="true"
           :aria-label="`${v.title?v.title:'標籤'+index}`">

        <image :src="currentPage === index ? v.activeIcon : v.icon"
               v-if="titleType === 'icon' && !titleUseSlot"
               :style="{ width: tabStyles.iconWidth + 'px', height:tabStyles.iconHeight+'px'}"/>

        <text class="icon-font"
              v-if="titleType === 'iconFont' && v.codePoint && !titleUseSlot"
              :style="{fontFamily: 'wxcIconFont',fontSize: tabStyles.iconFontSize+'px', color: currentPage === index ? tabStyles.activeIconFontColor : tabStyles.iconFontColor}">{{v.codePoint}}</text>

        <text
          v-if="!titleUseSlot"
          :style="{ fontSize: tabStyles.fontSize+'px', fontWeight: (currentPage === index && tabStyles.isActiveTitleBold)? 'bold' : 'normal', color: currentPage === index ? tabStyles.activeTitleColor : tabStyles.titleColor, paddingLeft:(tabStyles.textPaddingLeft?tabStyles.textPaddingLeft:10)+'px', paddingRight:(tabStyles.textPaddingRight?tabStyles.textPaddingRight:10)+'px'}"
          class="tab-text">{{v.title}}</text>
        <div class="border-bottom"
             v-if="tabStyles.hasActiveBottom && !titleUseSlot"
             :style="{ width: tabStyles.activeBottomWidth+'px', left: (tabStyles.width-tabStyles.activeBottomWidth)/2+'px', height: tabStyles.activeBottomHeight+'px', backgroundColor: currentPage === index ? tabStyles.activeBottomColor : 'transparent' }"></div>
        <slot :name="`tab-title-${index}`" v-if="titleUseSlot"></slot>
        
      </div>

      <div v-if="tabStyles.hasRightIcon"
           class="rightIcon"
           :style="{
            top: rightIconStyle.top,
            right: rightIconStyle.right,
            paddingLeft: rightIconStyle.paddingLeft,
            paddingRight: rightIconStyle.paddingRight
           }">
        <slot name="rightIcon"></slot>
      </div>

    </scroller>
    <div class="tab-page-wrap"
         ref="tab-page-wrap"
         @horizontalpan="startHandler"
         :style="{ height: (tabPageHeight-tabStyles.height)+'px' }">
      <div ref="tab-container"
           class="tab-container">
        <slot></slot>
      </div>
      <div class="line"></div>
    </div>
  </div>
</template>

<style scoped>
.wxc-tab-page {
  width: 750px;
}
.tab-title-list {
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.title-item {
  justify-content: center;
  align-items: center;
  border-bottom-style: solid;
}
.border-bottom {
  position: absolute;
  bottom: 0;
}
.tab-page-wrap {
  width: 750px;
  overflow: hidden;
}
.tab-container {
  flex: 1;
  flex-direction: row;
  position: absolute;
}
.tab-text {
  lines: 1;
  text-overflow: ellipsis;
}
.rightIcon {
  position: fixed;
  background-color: #ffffff;
  box-shadow: -50px 0 20px #ffffff;
}
.line {
  background-color: #ebebeb;
  width: 750px;
  height: 2px;
}
</style>

<script>
const dom = weex.requireModule("dom");
const animation = weex.requireModule("animation");
const swipeBack = weex.requireModule("swipeBack");
import { Utils, BindEnv } from "weex-ui";
//   import BindEnv from 'weex-ui';
import Binding from "weex-bindingx/lib/index.weex.js";
export default {
  props: {
    tabTitles: {
      type: Array,
      default: () => []
    },
    panDist: {
      type: Number,
      default: 200
    },
    spmC: {
      type: [String, Number],
      default: ""
    },
    titleUseSlot: {
      type: Boolean,
      default: false
    },
    tabStyles: {
      type: Object,
      default: () => ({
        bgColor: "#FFFFFF",
        titleColor: "#666666",
        activeTitleColor: "#3D3D3D",
        activeBgColor: "#FFFFFF",
        isActiveTitleBold: true,
        iconWidth: 70,
        iconHeight: 70,
        width: 160,
        height: 120,
        fontSize: 24,
        hasActiveBottom: true,
        activeBottomColor: "#FFC900",
        activeBottomWidth: 120,
        activeBottomHeight: 6,
        textPaddingLeft: 10,
        textPaddingRight: 10,
        leftOffset: 0,
        rightOffset: 0,
        normalBottomColor: "#F2F2F2",
        normalBottomHeight: 0,
        hasRightIcon: false
      })
    },
    titleType: {
      type: String,
      default: "icon"
    },
    tabPageHeight: {
      type: [String, Number],
      default: 1334
    },
    needSlider: {
      type: Boolean,
      default: true
    },
    isTabView: {
      type: Boolean,
      default: true
    },
    duration: {
      type: [Number, String],
      default: 300
    },
    timingFunction: {
      type: String,
      default: "cubic-bezier(0.25, 0.46, 0.45, 0.94)"
    },
    wrapBgColor: {
      type: String,
      default: "#f2f3f4"
    },
    clickAnimation: {
      type: Boolean,
      default: true
    },
    rightIconStyle: {
      type: Object,
      default: () => ({
        top: 0,
        right: 0,
        paddingLeft: 20,
        paddingRight: 20
      })
    }
  },
  data: () => ({
    currentPage: 0,
    gesToken: 0,
    isMoving: false,
    startTime: 0,
    deltaX: 0,
    translateX: 0
  }),
  created() {
    const { titleType, tabStyles } = this;
    if (titleType === "iconFont" && tabStyles.iconFontUrl) {
      dom.addRule("fontFace", {
        fontFamily: "wxcIconFont",
        src: `url(${tabStyles.iconFontUrl})`
      });
    }
  },
  mounted() {
    if (swipeBack && swipeBack.forbidSwipeBack) {
      swipeBack.forbidSwipeBack(true);
    }
    if (BindEnv.supportsEBForIos() && this.isTabView && this.needSlider) {
      const tabPageEl = this.$refs["tab-page-wrap"];
      Binding.prepare &&
        Binding.prepare({
          anchor: tabPageEl.ref,
          eventType: "pan"
        });
    }
  },
  methods: {
    next() {
      let page = this.currentPage;
      if (page < this.tabTitles.length - 1) {
        page++;
      }
      this.setPage(page);
    },
    prev() {
      let page = this.currentPage;
      if (page > 0) {
        page--;
      }
      this.setPage(page);
    },
    startHandler() {
      if (BindEnv.supportsEBForIos() && this.isTabView && this.needSlider) {
        this.bindExp(this.$refs["tab-page-wrap"]);
      }
    },
    bindExp(element) {
      if (element && element.ref) {
        if (this.isMoving && this.gesToken !== 0) {
          Binding.unbind({
            eventType: "pan",
            token: this.gesToken
          });
          this.gesToken = 0;
          return;
        }
        const tabElement = this.$refs["tab-container"];
        const { currentPage, panDist } = this;
        const dist = currentPage * 750;
        // x-dist
        const props = [
          {
            element: tabElement.ref,
            property: "transform.translateX",
            expression: `x-${dist}`
          }
        ];
        const gesTokenObj = Binding.bind(
          {
            anchor: element.ref,
            eventType: "pan",
            props
          },
          e => {
            const { deltaX, state } = e;
            if (state === "end") {
              if (deltaX < -panDist) {
                this.next();
              } else if (deltaX > panDist) {
                this.prev();
              } else {
                this.setPage(currentPage);
              }
            }
          }
        );
        this.gesToken = gesTokenObj.token;
      }
    },
    setPage(page, url = null, animated = true) {
      if (!this.isTabView) {
        this.jumpOut(url);
        return;
      }
      if (this.isMoving === true) {
        return;
      }
      this.isMoving = true;
      const previousPage = this.currentPage;
      const currentTabEl = this.$refs[`wxc-tab-title-${page}`][0];
      const { width } = this.tabStyles;
      const appearNum = parseInt(750 / width);
      const tabsNum = this.tabTitles.length;
      const offset = page > appearNum ? -(750 - width) / 2 : -width * 2;
      if (appearNum < tabsNum) {
        (previousPage > appearNum || page > 1) &&
          dom.scrollToElement(currentTabEl, {
            offset,
            animated
          });
        page <= 1 &&
          previousPage > page &&
          dom.scrollToElement(currentTabEl, {
            offset: -width * page,
            animated
          });
      }
      this.isMoving = false;
      this.currentPage = page;
      this._animateTransformX(page, animated);
      this.$emit("wxcTabPageCurrentTabSelected", { page });
    },
    jumpOut(url) {
      url && Utils.goToH5Page(url);
    },
    _animateTransformX(page, animated) {
      const { duration, timingFunction } = this;
      const computedDur = animated ? duration : 0.00001;
      const containerEl = this.$refs[`tab-container`];
      const dist = page * 750;
      animation.transition(
        containerEl,
        {
          styles: {
            transform: `translateX(${-dist}px)`
          },
          duration: computedDur,
          timingFunction,
          delay: 0
        },
        () => {}
      );
    }
  }
};
</script>

其中頂部tab的數據源改動後代碼 :

/**
 * Created by Tw93 on 2016/11/4.
 */

export default {

    tabTitles: [
      {
        title: '出借中',
        icon: 'https://gw.alicdn.com/tfs/TB1MWXdSpXXXXcmXXXXXXXXXXXX-72-72.png',
        activeIcon: 'https://gw.alicdn.com/tfs/TB1kCk2SXXXXXXFXFXXXXXXXXXX-72-72.png',
      },
      {
        title: '已完成',
        icon: 'https://gw.alicdn.com/tfs/TB1ARoKSXXXXXc9XVXXXXXXXXXX-72-72.png',
        activeIcon: 'https://gw.alicdn.com/tfs/TB19Z72SXXXXXamXFXXXXXXXXXX-72-72.png'
      }
    ],
    tabStyles: {
      bgColor: '#FFFFFF',
      titleColor: '#666666',
      activeTitleColor: '#3D3D3D',
      activeBgColor: '#FFFFFF',
      isActiveTitleBold: true,
      iconWidth: 70,
      iconHeight: 70,
      width: 280,
      height: 100,
      fontSize: 36,
      hasActiveBottom: true,
      activeBottomColor: '#FFC900',
      activeBottomHeight: 6,
      activeBottomWidth: 120,
      textPaddingLeft: 10,
      textPaddingRight: 10,
      normalBottomColor: '#fb4343',
      normalBottomHeight: 0,
      hasRightIcon: true,
      rightOffset: 0,
      
    },
    // 使用 iconfont 模式的tab title配置
    tabIconFontTitles: [
      {
        title: '首頁',
        codePoint: '\ue623'
      },
      {
        title: '特別推薦',
        codePoint: '\ue608'
      },
      {
        title: '消息中心',
        codePoint: '\ue752',
        badge: 5
      },
      {
        title: '我的主頁',
        codePoint: '\ue601',
        dot: true
      }
    ],
    tabIconFontStyles: {
      bgColor: '#FFFFFF',
      titleColor: '#666666',
      activeTitleColor: '#3D3D3D',
      activeBgColor: '#FFFFFF',
      isActiveTitleBold: true,
      width: 160,
      height: 120,
      fontSize: 24,
      textPaddingLeft: 10,
      textPaddingRight: 10,
      iconFontSize: 50,
      iconFontColor: '#333333',
      iconFontMarginBottom: 8,
      activeIconFontColor: 'red',
      iconFontUrl: '//at.alicdn.com/t/font_501019_mauqv15evc1pp66r.ttf'
    }
  }

 

2.在頁面中引用

上面我們將源碼修改好了,那麼接下來就是在weex頁面中編寫了。引用自定義的組件很關鍵。

1)在<script>標籤中導入自定義的組件

import tabTitleList from "@/utils/tabTitleList";
import ZengTabPage from "@/components/zeng-tab-page";

注意:這裏一定要注意自定義組件的命名規則

2)在<template>標籤中使用

<zeng-tab-page ref="wxc-tab-page"
                :tab-titles="tabTitles"
                :tab-styles="tabStyles"
                title-type="text"
                :tab-page-height="tabPageHeight"
                @wxcTabPageCurrentTabSelected="wxcTabPageCurrentTabSelected">
    
    <list v-for="(v,index) in tabList"
          :key="index"
          class="item-container"
          :style="{ height: (tabPageHeight - tabStyles.height) + 'px' }">
      <!-- <cell class="border-cell"></cell> -->
      <cell v-for="(demo,key) in v"
            class="cell"
            :key="key">
            <!-- url="https://h5.m.taobao.com/trip/ticket/detail/index.html?scenicId=2675" -->
        <wxc-pan-item :ext-id="'1-' + (v) + '-' + (key)"
                      @wxcPanItemClicked="wxcPanItemClicked(demo,key)"
                      @wxcPanItemPan="wxcPanItemPan">
         <div class="content">
            <text>{{demo.productName}}</text>
         </div>
        </wxc-pan-item>
      </cell>
    </list>
  </zeng-tab-page>

說明:自定義組件在源碼的基礎上改動的話,原來自帶的屬性,比如:tab-titles="tabTitles"、:tab-styles="tabStyles"、title-type="text"這些屬性是不會變的。

最後我們將項目進行編譯運行如圖:

由於代碼較多,就不把全部代碼貼出來,在開發中遇到坑的同學可以評論中討論。生命不止,學習不停!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章