- 首页
- 前端开发
- 在 v-for 项目内切换会影响整个列表,如何使每个切换仅影响包含列表项?
在 v-for 项目内切换会影响整个列表,如何使每个切换仅影响包含列表项?
[英] Toggle inside v-for items affects the entire list, how can I make the each toggle affect only the containing list item?
本文介绍了在 v-for 项目内切换会影响整个列表,如何使每个切换仅影响包含列表项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 v-for 循环制作项目列表.在循环的每个项目中,都有带有单击事件方法的按钮,用于显示描述文本.当我点击按钮时,它应该只在它自己的项目内切换,但它会影响 v-for 列表中的所有元素.
那么,如何制作一个只影响它自己的项目的切换方法?
<div><div v-for="item in items" :class="{ activeclass: isActive }"><div class="item-text">{{item.text}}
<button @click="toggle()">show</button><div v-show="isActive" class="item-desc">{{item.desc}}
</模板><脚本>导出默认{数据 () {返回 {项目: [{文字:'福',desc: 'Array.from() 方法从一个类似数组或可迭代的对象创建一个新的 Array 实例.',},{文字:'酒吧',desc: 'Array.from() 方法从一个类似数组或可迭代的对象创建一个新的 Array 实例.',}],isActive: 假}},方法: {切换:函数(){this.isActive = !this.isActive;}},}
解决方案
正如@Nora 所说,您可以(并且可能应该)为每个列表项创建一个单独的组件,因此您将拥有一个接受 项的组件
作为一个 prop,那么每个组件都可以有自己的 isActive
标志,这样可以保持标记干净整洁:
组件:
Vue.component('toggle-list-item', {模板:'#list-item',道具:['物品'],方法: {切换(){this.isActive = !this.isActive;}},数据() {返回 {isActive: 假}},})
标记
现在您可以简单地将组件放置在您的 v-for
中:
<div v-for="项目中的项目"><toggle-list-item :item="item"></toggle-list-item>
这是 JSFiddle:https://jsfiddle.net/w10qx0dv/
I'm making a list of items with v-for loop. Inside each item of the loop there is button with click event method that showing description text.
When i click on the button, it should toggle only inside it's own item, but it affecting all elements in v-for list.
So, how to make a toggle method that will affect only it's own item?
<template>
<div>
<div v-for="item in items" :class="{ activeclass: isActive }">
<div class="item-text">
{{item.text}}
</div>
<button @click="toggle()">show</button>
<div v-show="isActive" class="item-desc">
{{item.desc}}
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
items: [
{
text: 'Foo',
desc: 'The Array.from() method creates a new Array instance from an array-like or iterable object.',
},
{
text: 'Bar',
desc: 'The Array.from() method creates a new Array instance from an array-like or iterable object.',
}
],
isActive: false
}
},
methods: {
toggle: function () {
this.isActive = !this.isActive;
}
},
}
</script>
解决方案
As @Nora said you can (and probably should) create a separate component for each list item, so you would have a component that accepts an item
as a prop, then each component can have it's own isActive
flag, which keeps the markup nice and clean:
Component:
Vue.component('toggle-list-item', {
template: '#list-item',
props: ['item'],
methods: {
toggle() {
this.isActive = !this.isActive;
}
},
data() {
return {
isActive: false
}
},
})
Markup
Now you can simply place the component inside your v-for
:
<div id="app">
<div v-for="item in items">
<toggle-list-item :item="item"></toggle-list-item>
</div>
</div>
Here's the JSFiddle: https://jsfiddle.net/w10qx0dv/
这篇关于在 v-for 项目内切换会影响整个列表,如何使每个切换仅影响包含列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!