Case study:

Results :(exceeded expectations, not only made a fixed width, but also with an indefinite width, applaud myself ~)

After analyzing the demand, in the TAB, select the option at the top with a line, then, on the line when the mouse hover will slide to the corresponding option, at this moment if selected, line will stay on the selected option, if not checked, then it will slip back into position before (that is, the selected option will always have this line)

After reading the requirements, it was discovered that this line could not be implemented using the element’s border attribute or pseudo-class because it needs to be slid (away from the element itself).

So the first thing that came to my mind was to write a separate element, and to do that by positioning.

Tabs are generally implemented in UL, and this is no exception. Write the body first

<ul class="noqLengthUl"> <span class="navBg"></span> <li v-for="(item, index) in noqtab" :key="item.id" :class="{active: index == nowIndex}" @click="changeTab($event, index)"> <a href="javascript:;" >{{item.value}}</a> </li> </ul>Copy the code

The style part is omitted, this is too easy. Note: Li is fixed width!!

Take a look at the Data section of vUE

NowIndex: 0, noqtab: [{id: 'noqtab1', value: 'noqtab1'}, {id: 'noqtab2', value: 'learn that'}, {id: 'noqtab3', value: 'learn that'}, {id: 'noqtab3', value: 'entertainment it'}, {value: id: 'noqtab4', 'about us'}, {id:' noqtab5, value: 'product center'}, {id: 'noqtab6, value:' contact us'}]Copy the code

Look at the effect

This is the most common TAB at this point, and whichever one is selected, a style will be added to make it different from the others. The line above the home page of the website is our protagonist. First, we position it at ul Left :0, because it is fixed width, so the width should be consistent with Li, and the next step is to let it slide with the mouse hover.

Since it is hover, it is mouse event, since there is no hover event in Vue, so I use @mouseenter and @mouseleave to implement it.

Since the TAB is fixed-width, all you need to do is change its left when the mouse enters and leaves. Here’s how:

changeBgPos(el, index){
  this.$refs.noNavBg.style.left = `${(index)*90}px`;
},
backBgPos(el, index){
  let bgLeft = document.querySelector(".noqLengthUl li.active").offsetLeft;
  this.$refs.noNavBg.style.left = `${bgLeft}px`;
},
Copy the code

This is done by using ref with $refs, adding events to the HTML

<ul class="noqLengthUl"> <span class="navBg" ref="noNavBg"></span> <li v-for="(item, index) in noqtab" :key="item.id" :class="{active: index == nowIndex}" @click="changeTab($event, index)" @mouseenter="changeBgPos($event, index)" @mouseleave="backBgPos($event, index)"> <a href="javascript:;" >{{item.value}}</a> </li> :class="{active: index == nowIndex}" </ul>Copy the code

This is the end result!

So, what do you do with a variable width TAB? This problem is left to everyone to ponder first party ~