A
A
Aleksandr_KH2019-07-03 12:18:51
Vue.js
Aleksandr_KH, 2019-07-03 12:18:51

How to add and remove the class of neighboring blocks?

Hello.
I have two buttons. Button1 and Button2.
How can I add the active class to it by clicking on Button1, and remove the Active class from Button2 by clicking on Button2, and add it to Button2 accordingly (Active class). This is the first task.
The second task, there is also a block (Block), I need that by clicking on Button1, for example, the test1 class is hung on Block, and by clicking on Button2, the test1 class is deleted and the test2 class is added instead.
By and large, this should work roughly like tabs, but I could not find a normal simple solution.
For a complete understanding, I sketched the markup .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-07-03
@Aleksandr_KH

We put the data of buttons and blocks into an array, we also add a property to the component - a link to the active element of the array (this is the button whose button should receive the active class and the class of which should be assigned to the block):

data: () => ({
  items: [
    { buttonTitle: '...', blockClass: '...' },
    { buttonTitle: '...', blockClass: '...' },
    ...
  ],
  active: null,
}),

Based on the array, we create buttons, on click we set the value of the active element:
<button
  v-for="n in items"
  :class="{ active: active === n }"
  @click="active = n"
>{{ n.buttonTitle }}</button>

Accordingly, if the active element is not null, we show the block by assigning a class to it:
<div v-if="active" :class="[ 'block', active.blockClass ]">

https://jsfiddle.net/bwmk7f1t/

E
Evgeny Kulakov, 2019-07-03
@kulakoff Vue.js

<button v-for="button in 2" :key="button" @click="active = button" :class="{active: active === button}">button</button>
<div id="block" :class="`test${active}`">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question