js模拟增删
html
首先是一个大的容器container 然后分成上部和下部分 上部放着增加和全部删除按钮
下面是for循环遍历数组
<div class="container">
<div class="topview">
<div class="btnview" onclick="add">
<text>增加</text>
</div>
<div class="btnview" onclick="delall"><text>全部删除</text></div>
</div>
<div class="contentview">
<block for="{{arrdatas}}">
<div class="boxview">
<text>{{$item}}</text>
<button type="text" onclick="delitem({{$idx}})">删除</button>
</div>
</block>
</div>
</div>
css
.container {
display: flex;
flex-direction: column;
width: 100%;
overflow: scroll;
/* overflow: scroll;*/
}
.topview{
width: 100%;
height: 18%;
display: flex;
align-items: center;
justify-content: space-around;
background-color: powderblue;
}
.btnview{
background-color: burlywood;
width: 40%;
height: 30%;
display: flex;
justify-content: center;
align-items: center;
border-radius: 10vp;
}
.contentview{
width: 100%;
display: flex;
flex-direction: column;
}
.boxview{
width: 100%;
height: 10%;
border-bottom: 2vp solid olivedrab;
background-color: antiquewhite;
display: flex;
justify-content: space-around;
align-items: center;
}
js
delall方法是删除全部数据 通过将arrdatas赋为空来模拟删除全部数据
add方法是通过调用Math.random方法来生成随机数然后通过push来添加到arrdatas数组中
delitem方法是通过html onclick绑定方法传数组下表到js中进行删除 点击删除会弹出提示框 进一步确实是否确认删除 arrdatas.splice(index,num), 第一个参数为第一项位置,第二个参数为要删除几个。
import prompt from '@system.prompt';
export default {
data: {
arrdatas:[]
},
onInit(){
for(let i = 0; i <= 20; ++i) {
this.arrdatas.push("第"+i+"项");
}
},
delall() {
this.arrdatas = [];
},
add() {
let rv = parseInt(Math.random()*11);
console.log("随机数是:"+rv);
console.log(typeof rv);
this.arrdatas.push("随机数项为"+rv+"项");
},
delitem(index) {
console.log("点击删除项的索引就是下标"+index);
prompt.showDialog({
title:"操作提示",
message:"你确定删除这条数据吗?",
buttons:[{"text":"确认","color":"#000000"},
{"text":"取消","color":"#000000"}],
success:(event)=>{
console.log(event);
console.log(typeof event);
console.log(JSON.stringify(event));
if(event.index == 0) this.arrdatas.splice(index, 1);
if(event.index == 1) {
prompt.showToast({
message:"你取消了删除操作",
duration:6000
})
}
}
})
}
}