The idea of vue is to manipulate dom through data, so we traverse dom according to the data in data, so that we can dynamically add or delete vue by manipulating data!
<template>
<div>
<input
v-model="inpValue"
type="text"
placeholder="请输入添加文字"
@blur="addList"
/>
<ul v-if="list.length > 0">
<li v-for="(item, index) in list" :key="index">
{
{ item }} <span @click="removeList(index)">X</span>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
inpValue: "",
};
},
methods: {
// 向list数组内添加
addList() {
// 判断输入框不为空
if (this.inpValue) {
// 查重
const isIncludes = this.list.includes(this.inpValue);
if (!isIncludes) {
this.list.push(this.inpValue);
this.inpValue = "";
} else {
alert("添加重复");
this.inpValue = "";
}
}
},
// 向数组中删除元素
removeList(index) {
this.list.splice(index, 1);
},
},
};
</script>
<style scoped>
div {
width: 1200px;
margin: 100px auto;
}
input {
width: 400px;
border: 1px solid #eee;
border-radius: 5px;
height: 30px;
line-height: 30px;
}
ul {
margin: 20px 0;
padding: 0;
list-style-type: none;
width: 400px;
}
li {
border: 1px solid #ccc;
margin: 10px 0;
position: relative;
}
span {
position: absolute;
cursor: pointer;
right: 10px;
color: red;
}
</style>