用vue实现一个内容显示或隐藏的功能。要求:1.点击按钮可以将内容隐藏,并将隐藏的内容保存在一个数组当中,2.可以查看隐藏的内容,3.内容是由列表渲染出来并且只能对列表中的某一条数据进行显示隐藏,4.有删除内容按钮并且有卸载的进度条
时间: 2024-03-21 12:41:44 浏览: 19
好的,以下是实现代码:
```
<template>
<div>
<ul>
<li v-for="(item, index) in list" :key="index">
{{ item.text }}
<button @click="toggle(index)">
{{ item.show ? '隐藏' : '显示' }}
</button>
<button @click="remove(index)">删除</button>
</li>
</ul>
<div v-if="hiddenList.length > 0">
<h3>隐藏内容</h3>
<ul>
<li v-for="(item, index) in hiddenList" :key="index">{{ item.text }}</li>
</ul>
</div>
<button @click="uninstall">卸载</button>
<div v-if="uninstalling" class="progress-bar"></div>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{ text: '内容1', show: true },
{ text: '内容2', show: true },
{ text: '内容3', show: true },
],
hiddenList: [],
uninstalling: false,
};
},
methods: {
toggle(index) {
const item = this.list[index];
item.show = !item.show;
if (!item.show) {
this.hiddenList.push(item);
} else {
this.hiddenList.splice(this.hiddenList.indexOf(item), 1);
}
},
remove(index) {
const item = this.list[index];
if (!item.show) {
this.hiddenList.splice(this.hiddenList.indexOf(item), 1);
}
this.list.splice(index, 1);
},
uninstall() {
this.uninstalling = true;
setTimeout(() => {
this.$destroy();
}, 2000);
},
},
};
</script>
<style>
.progress-bar {
width: 100%;
height: 20px;
background-color: #ddd;
position: relative;
}
.progress-bar:before {
content: '';
display: block;
width: 0%;
height: 100%;
background-color: #3498db;
position: absolute;
top: 0;
left: 0;
transition: width 2s;
}
.uninstalling .progress-bar:before {
width: 100%;
}
</style>
```
实现思路:
1. 在 data 中定义 list 数组,每个元素包含 text 和 show 两个属性,text 用于显示内容,show 用于标记是否显示。
2. 使用 v-for 渲染出列表,并绑定按钮的点击事件。
3. 点击按钮后,将对应的 show 属性取反,同时将该元素添加到 hiddenList 数组中(如果原本是显示的),或从 hiddenList 数组中删除(如果原本是隐藏的)。
4. 点击删除按钮后,先判断该元素是否是隐藏状态,如果是,则从 hiddenList 中删除,再从 list 中删除。
5. 点击卸载按钮后,设置 uninstalling 属性为 true,同时使用 setTimeout 模拟一个卸载进度条,进度条完成后调用 $destroy 方法卸载组件。
注意:为了实现卸载进度条,需要在样式中添加一个 .progress-bar:before 选择器,并使用 before 伪元素来表示进度条的进度。在卸载时,将 .uninstalling 类添加到 .progress-bar 上,即可触发进度条的动画。