Переключение активных элементов
Есть список из шести элементов, как сделать так , чтобы допустим , я нажал на 5-тый блок , active_el присвоилось 5 , а при помощи v-if который установлен на блок , отобразился только 5-тый блок, если я нажму допустим на второй элемент , пятый скроется , а отобразиться второй ?
const app = new Vue({
el: '#app',
data() {
return {
active_el: 0,
headerItems: [
{id: 0, text: 'Один'},
{id: 1, text: 'Два'},
{id: 2, text: 'Три'},
{id: 3, text: 'Четыре'},
{id: 4, text: 'Пять'},
{id: 5, text: 'Шесть'},
],
}
},
methods: {
activate (el){
this.active_el = el;
},
},
});
ul li {
list-style: none;
}
.header__list {
display: flex;
width: 1311px;
height: 30px;
position: absolute;
top: 30px;
left: calc(50% - 350px/2);
}
.header__item {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
padding: 0px;
cursor: pointer;
margin-right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul class="header__list">
<li class="header__item"
v-for="(headerItem, item) in headerItems"
:key="item.id"
@click="activate(item.id - 1)">
<p :class="headerItem.class">{{headerItem.text}}</p>
</li>
</ul>
<div class="pervii" v-if="active_el === 0">Привет 0</div>
<div class="vtoroi" v-if="active_el === 1">Привет 1</div>
<div class="tretii" v-if="active_el === 2">Привет 2</div>
<div class="tretii" v-if="active_el === 3">Привет 3</div>
<div class="tretii" v-if="active_el === 4">Привет 4</div>
<div class="tretii" v-if="active_el === 5">Привет 5</div>
</div>
Ответы (1 шт):
Автор решения: Dmitrii Sedov
→ Ссылка
Ну проблема в том, что в item нет id. Так как это индекс массива. Смотрите внимательно что вы в v-for по написали. Так же откуда взялся headerItem.class? которого в принципе нигде не объявлено
Столько v-if нельзя делать. Не дублируйте код!! Ниже пример как сделать чуть по другому
const app = new Vue({
el: '#app',
data() {
return {
active_el: null,
headerItems: [
{id: 0, text: 'Один'},
{id: 1, text: 'Два'},
{id: 2, text: 'Три'},
{id: 3, text: 'Четыре'},
{id: 4, text: 'Пять'},
{id: 5, text: 'Шесть'},
],
}
},
created() {
this.active_el = this.headerItems[0];
},
methods: {
activate (el){
this.active_el = el;
},
},
});
ul li {
list-style: none;
}
.header__list {
display: flex;
width: 1311px;
height: 30px;
position: absolute;
top: 30px;
left: calc(50% - 350px/2);
}
.header__item {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
padding: 0px;
cursor: pointer;
margin-right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul class="header__list">
<li class="header__item"
v-for="headerItem in headerItems"
:key="headerItem.id"
@click="activate(headerItem)">
<p :class="headerItem.class">{{headerItem.text}}</p>
</li>
</ul>
<div class="pervii" v-if="active_el">{{active_el.text}}</div>
</div>