vue动态添加/删除dom元素

vue的思想是通过数据操作dom,所以我们根据data中的数据进行对dom的遍历,从而操作数据就可以对vue进行一个动态的添加或者删除啦!
<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>