W
W
wakenby2021-01-16 20:39:17
Vue.js
wakenby, 2021-01-16 20:39:17

How to create tabs in vue?

I want to create such tabs:
600323ffcf3f3580063780.png

So that when the active button is changed, the line moves (travels) to the active button. But I don’t understand how to do this, it’s bad practice to work with dom directly, but I can’t even imagine how to do it using vue

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2021-01-16
@wakenby

working with dom directly is bad practice

Not always. Depends on the task.
Let the tabs component take as parameters an array of values ​​describing the tabs and a value denoting the active tab: In the component's data, we put the styles for the element representing the underline of the active tab:
props: [ 'items', 'value' ],
data: () => ({
  sliderStyles: null,
}),

Let's create the tabs and the underscore element ourselves:
<ul class="tabs">
  <li
    v-for="n in items"
    :key="n.value"
    @click="$emit('input', n.value)"
    class="tabs-item"
  >{{ n.text }}</li>
</ul>
<div
  class="tabs-slider"
  :style="sliderStyles"
></div>

Let's give the underline ( .tabs-slider) element absolute positioning and a transition.
Set up tracking of the current value - find out its index among the values ​​available for selection, write the position and size of the tab with the corresponding index into the styles of the underline element:
mounted() {
  this.$watch(
    'value',
    value => {
      const index = this.items.findIndex(n => n.value === value);
      const el = this.$el.querySelectorAll('.tabs-item')[index];
      this.sliderStyles = el
        ? {
            left: `${el.offsetLeft}px`,
            width: `${el.offsetWidth}px`,
          }
        : null;
    },
    {
      immediate: true,
    }
  );
},

https://jsfiddle.net/vsr5tLue/

T
Tigran Abrahamyan, 2021-01-16
@TAbrahamyan

https://jsfiddle.net/78ksdon0/

D
Dmitry, 2021-01-16
@DKWLB

You seem to have mixed everything together. tabs or buttons?
switching active items can be done through vue-router
or like this (found by search),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question