版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31126175/article/details/82190534
无组件
效果图
代码
<template>
<div>
<div v-for="(item,index) in list" :key="index" @click="select(index)" :class="[{'active': activeIndex == index},'box']">
<span>{{item.name}}</span>
<button v-show="!item.open" @click="openfun(item)">展开</button>
<span v-show="item.open">{{item.text}}</span>
</div>
</div>
</template>
<script>
export default {
data(){
return {
list:[
{
name:'1111',
text:'wwwwwwwwwwwww',
open:false
},
{
name:'2222',
text:'qqqqqqqqqqqqqq',
open:false
},
{
name:'3333',
text:'aaaaaaaaaaaaa',
open:false
},
{
name:'4444',
text:'ssssssssssssss',
open:false
},
],
activeIndex:0,
}
},
watch:{
},
methods:{
select(val){
this.activeIndex = val;
},
openfun(val){
this.list.forEach(element => {
element.open = false;
});
val.open = true;
}
}
}
</script>
<style>
.box{
width: 300px;
height:60px;
background-color: blue;
}
.active{
border:1px solid red;
}
</style>
说明
1、选中样式
设定一个activeIndex 当activeIndex 与数据索引一致时,有选中样式。
2、展开按钮(只展开一个)
我们需要每一项都有一个是否展开的值,所以在数据里添加一个open的值来控制,点击的时候,先将所有的都合上,再把当前的打开。
有组件
数据列表不好改变时,使用组件开发
效果图
父组件
<template>
<div style="">
<div >
<open v-for="(item,index) in list" :key="index" :data='item' :index='index' :activeIndex='activeIndex' @selectbox='activebox'></open>
</div>
</div>
</template>
<script>
import open from './open'
export default {
components:{open},
data(){
return {
list:[
{
name:'1111'
},
{
name:'2222'
},
{
name:'3333'
},
{
name:'4444'
},
],
activeIndex:0,
}
},
methods:{
activebox(val){
console.log('val',val);
this.activeIndex = val;
console.log('active',this.activeIndex);
}
}
}
</script>
<style>
</style>
子组件
<template>
<div @click="select(index)" :class="[{'active': activeIndex == index},'box']">
<span>{{data.name}}</span>
<button v-show="openbtn" @click="openfun(index)">展开</button>
<span v-show="openshow">wwwwwwwwwwwww</span>
</div>
</template>
<script>
export default {
name:'open',
data(){
return {
openbtn:true,
openshow:false,
}
},
props:['data','index','activeIndex'],
watch:{
activeIndex(val,oldval){
if(this.index != val){
this.openbtn = true;
this.openshow = false;
}
}
},
methods:{
select(val){
console.log('open',val);
this.$emit('selectbox',val)
},
openfun(index){
this.openbtn = false;
this.openshow = true;
}
}
}
</script>
<style>
.box{
width: 300px;
height:60px;
background-color: blue;
}
.active{
border:1px solid red;
}
</style>
说明
父组件 遍历子组件 向子组件传入 数据 ,index ,activeIndex
1、选种样式
子组件通过 判断 当前组件的index 与activeIndex 是否一致 ,一致则有选中样式
activeIndex 只有一个值,存在父组件里,当子组件click 时 ,把子组件的index向父组件的activeIndex传值
2、展开项
每个组件维护一个openbtn 和openshow
监听activeIndex 变化时,比较activeIndex与index ,判断是否选中,未选中的恢复到默认值即可。点击展开按钮,改变值。
此方法仅供参考,有更好的方法,可以告知我,谢谢。