美文网首页
5.用ES6写组件步骤(选项卡案例)

5.用ES6写组件步骤(选项卡案例)

作者: 谷子多 | 来源:发表于2018-01-07 16:37 被阅读0次

    组件 :

         方便复用,特别是一些复用率高的功能。

        思路 : 通过传入大的父级,就可以调用选项卡

    步骤:

        1.先确定可配置项:

            宽 :width

            高 :height

            取消触发函数 : cancelFn

            是否拖拽 :isDrag

            内容:content

        2.新建一个类

             (1)constructor里建变量,opt是配置项

             (2)使用Object.assign(),用配置项覆盖默认opt

             (3)调用init(初始化代码,也就是基础逻辑在这个方法里面)    

            (4)将功能模块拆分,仔细分析实现这个需求需要的功能,一个功能写一个方法,降低耦合。

            (5)在init中调用各方法


    class Tab{

    //1

        constructor(obj){

    this.opt= {

    obj: null,

                btns: ['新闻','体育','娱乐','社会'],

                contents: ['十八大召开','科比退役','郑爽','房价下跌'],

                width: 200,

                height: 150,

                isDrag: false

            }

    //2.右值赋给左值:如果有配置,就会覆盖opt,如果没有配置,就运行opt中的参数

            Object.assign(this.opt,obj)

    this.box= document.querySelector(this.opt.obj)

    this.init()

    }

    //2

        init(){//初始化

            this.creatBtns()

    this.creatDiv()

    this.events()

    this.boxStyle()

    //是否调用拖拽

            /*if(this.isDrag){

    new Drag()

    }*/

        }

    //3

        creatBtns(){

    let html= ''

            this.opt.btns.forEach((el,i)=>{

    html+=`${el}`

            })

    this.box.innerHTML= html

    }

    creatDiv(){

    let html= ''

            this.opt.contents.forEach((c,i)=>{

    html+=`

    ${c}

    `

            })

    this.box.innerHTML+= html

    }

    events(){

    this.btns= Array.from(document.querySelectorAll('button'))

    this.divs= this.box.querySelectorAll('div')

    let that= this

            this.btns.forEach((e,i)=>{

    e.onclick = function(){

    that.change(i)

    }

    })

    }

    change(index){

    this.btns.forEach((e,i)=>{

    e.className= ''

                this.divs[i].className=''

            })

    this.btns[index].className= 'active'

            this.divs[index].className= 'show'

        }

    boxStyle(){

    this.box.style.cssText=`width:${this.opt.width}px;height:${this.opt.height}px`

        }

    }

    let t = new Tab({

    obj: '#box',

        width: '500'

    })

    相关文章

      网友评论

          本文标题:5.用ES6写组件步骤(选项卡案例)

          本文链接:https://www.haomeiwen.com/subject/nyzpnxtx.html