用 es6 完成一个简朴可复用的 tab 组件

结果

《用 es6 完成一个简朴可复用的 tab 组件》

这是用 es6 + jq 写的一个简朴的 tab 组件,也能够直接 点这里 看结果。

剖析

这里采用了 es6 的新特征 class 来天生一个组件,固然,用 es5 的 prototype 也能够模仿。

class Tab {
  constructor(opts) {
    this.index = opts.index || 0; 
    this.$tabHeader = opts.header; 
    this.$tabBody = opts.body;
    this.render();
    this.bind();
  }
  render() {
    this.$tabHeader.find("li").eq(this.index).addClass("active").siblings().removeClass("active");
    this.$tabBody.find("li").eq(this.index).show().siblings().hide();
  }
  bind() {
    this.$tabHeader.on("click", "li", e => {
      this.index = $(e.target).index();
      this.render();
    });
  }
}

let tab = new Tab({
  header: $(".tab-header"),
  body: $(".tab-body")
})

constructor:

  • 组件的进口是 constructor 组织函数,es5 的话能够写个 init 函数来替代。

  • 用来初始化一些成员变量,个中 index 是值当前显现的第几页,假如没有传值,则默许显现第一页。

render:

  • 依据当前 index 衬着头部和身材。

  • 第一句话是给头部当前 index 加上 “active” 的款式,而且去撤除别的 li 已有的 “active”款式。

  • 第二句话是将身材当前 index 显现出来,而且隐蔽兄弟 li 元素。

bind

  • 老样子,绑定事宜。

  • 给头部举行事宜托付,点击恣意一个 li 则转变当前 tab 组件的 index 值,然后从新挪用 render 要领衬着一下。

  • 用了箭头函数,能够让作用域一直指向 Tab 这个组件,就能够免除分外声明一个 self 来处理作用域题目啦。

  • 用了箭头函数就没有 this 了,那末能够 用 e.target 来猎取当前点击的 dom 对象。

总结

两个知识点:

  1. class

  2. arrow function

假如有什么想跟我议论的话,请私信。
    原文作者:viewweiwu
    原文地址: https://segmentfault.com/a/1190000007480765
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞