实现简单的添加、删除、上下移动,批量删除
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
ul {
padding: 0;
}
li {
margin: 5px 0;
list-style: none;
height: 30px;
}
</style>
</head>
<body>
<div id="app">
<add-list @add="add"></add-list>
<list-content :arrlist="arrList" @remove="removed" @removeall="removeall" @topMove="topmove"
@bottomMove="bottommove">
</list-content>
</div>
<script src="./Vue.js"></script>
<script>
//按钮组件
const BtnGroup = {
props: ["text"],
template: `<button>{{text}}</button>`
}
//添加组件
const AddList = {
data() {
return {
addInput: "",
}
},
template: `<div>
<input type="text" v-model="addInput">
<button @click="add">添加</button>
</div>`,
methods: {
add() {
this.$emit("add", this.addInput);
this.addInput = "";
}
}
};
//列表组件
const ListContent = {
data() {
return {
checkNames: [],
}
},
props: ["arrlist"],
template: `<ul>
<li v-for="(v,i) of arrlist" :key="v.id"><input type="checkbox" :value="v" v-model="checkNames">
<span :style="{textDecoration:checkNames.includes(v)?'line-through':''}">{{v.name}}</span>
<span v-if="checkNames.includes(v)">
<btn-group text="删除" @click.native="remove(i)"></btn-group>
<btn-group text="上移" @click.native="topmove(i)"></btn-group>
<btn-group text="下移" @click.native="bottommove(i)"></btn-group>
</span>
</li>
<div>
<btn-group text="批量删除" v-if="arrlist.some((v) => this.checkNames.includes(v))"
@click.native="removeall(checkNames)">
</btn-group>
</div>
</ul>`,
methods: {
remove(i) {
this.$emit("remove", i)
},
removeall(i) {
this.$emit("removeall", i)
},
//上移
topmove(i) {
this.$emit("topmove", i)
},
//下移
bottommove(i) {
this.$emit("bottommove", i)
}
},
components: {
BtnGroup
}
}
new Vue({
el: "#app",
data: {
arrList: [{
id: 1,
name: "更合适的"
}, {
id: 2,
name: "地方"
}, {
id: 3,
name: "很大的"
}],
},
methods: {
add(s) {
if (!s == '') {
this.arrList.push({
id: new Date().getTime(),
name: s
})
}
},
removed(i) {
this.arrList.splice(i, 1);
},
removeall(s) {
s.forEach((sId) => {
if (this.arrList.findIndex((v) => v.id === sId.id) !== -1) {
this.arrList.splice(this.arrList.findIndex((v) => v.id === sId.id), 1);
}
})
},
topmove(i) {
if (i === 0) {
console.log("不能移动了,到顶了");
} else {
// let v = this.arrList[i];
// this.arrList[i] = this.arrList[i - 1];
// this.arrList[i - 1] = v;
//直接改变数组项是不响应的
this.arrList.splice(i - 1, 2, this.arrList[i], this.arrList[i - 1]);
}
},
bottommove(i) {
if (i === this.arrList.length - 1) {
console.log("不能移动了,到底了");
} else {
this.arrList.splice(i, 2, this.arrList[i + 1], this.arrList[i]);
}
}
},
components: {
AddList,
ListContent,
}
});
</script>
</body>
</html>