// 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) } }) } }) }
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一开始会从左往右滑 }) }
// 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)` }) }) }
// 增长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) } }
<img src="https://i.loli.net/2020/01/27/gS4ZwP6zfAvULYT.jpg" alt="微信" width="400" height="400" align="bottom" /> > 本文由博客一文多发平台 [OpenWrite](https://openwrite.cn?from=article_bottom) 发布! vue