Vue造轮子-Tabs测试(上)

1. 点击出现下划线的问题

    // tabs-item.vue
    methods: {
      xxx() {
        this.eventBus.$emit('update:selected', this.name, this) 
      }
    }
    // tabs.vue
    mounted(){
      this.eventBus.$emit('update:selected', this.selected) 
    }
    // tabs-head
    created(){
      this.eventBus.$on('update:selected', (item, vm) => {
        console.log(item)
        console.log(vm) // 初始化的时候打印出的值为undefined 
      })
    }
    
    // 为了解决初始化打印出为undefined的问题
    // tabs.vue 通过两层循环解决找到item
    mounted(){
      this.$children.forEach((vm)=>{
        if(vm.$options.name === 'GuluTabsHead'){ // 找儿子
          vm.$children.forEach((childVm)=>{ // 找孙子
            if(childVm.$options.name === 'GuluTabsItem' && childVm.name === this.selected){
              this.eventBus.$emit('update:selected', this.selected,childVm)
            }
          })
        }
      })
    }

2. 找到item之后开始做动画

 mounted(){
      this.eventBus.$on('update:selected', (item, vm) => {
        let {width, height, top, left} = vm.$el.getBoundingClientRect()
        this.$refs.line.style.width = `${width}px` // 宽度就会跟着我们点的元素的宽度变,
        // this.$refs.line.style.left = `${left}px` // 宽度变了我们再修改位置
        this.$refs.line.style.transform = `translateX(${left}px)` 
        // 可以这样优化写来实现硬件3d加速
        // 但是这样写有个bug一开始会从左往右滑
      })
    }

3. 尝试解决一开始从走往右滑动的bug

  // tabs-head.vue
    <template>
        <div class="tabs-head">
            <slot></slot>
                <div class="line" ref="line" v-if="x"></div>
            </div>
        </div>
    </template>

    data(){
      return {
        x: false
      }
    },
    mounted(){
      this.eventBus.$on('update:selected', (item, vm) => {
        this.x = true
        // 新增一个[更新UI任务]到任务队列里面,
        // 会先把下面js执行完了再更新,所以 this.$refs.line.style.width会报错
        // 我们只要把代码放到[更新UI任务]的后面就能解决
        this.$nextTick(()=>{
          // 新增一个函数,放到任务队列里面,由于[更新UI任务]是先放进去那么就会先执行
          // 但是这样做还是没解决从左往右滑的bug,所以还是改回left
          let {width, height, top, left} = vm.$el.getBoundingClientRect()
          this.$refs.line.style.width = `${width}px`
          this.$refs.line.style.transform = `translateX(${left}px)`
        })
      })
    }

4.增加禁用功能和禁用样式

    // 增加disabled样式
    computed: {
      classes() { // classes是一个计算属性
        return {
          active: this.active,
          disabled: this.disabled,
        }
      }
    },
    // 增加disabled行为
    methods: {
      onClick() {
        if (this.disabled) {
          return
        }
        this.eventBus.$emit('update:selected', this.name, this)
      }
    }

最后,欢迎交流!

微信
posted @ 2020-01-28 21:53  Ories  阅读(197)  评论(0编辑  收藏  举报