vue实现列表添加
使用 Vue 实现列表添加功能
数据绑定与列表渲染
在 Vue 中,通过 v-for 指令可以轻松实现列表渲染。首先需要定义一个数组来存储列表数据,并在模板中使用 v-for 循环渲染。
<template>
<div>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3']
}
}
}
</script>
添加新项到列表
通过 v-model 绑定输入框的值,并在方法中使用 push 将新项添加到数组。

<template>
<div>
<input v-model="newItem" placeholder="Add new item">
<button @click="addItem">Add</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
newItem: ''
}
},
methods: {
addItem() {
if (this.newItem.trim() !== '') {
this.items.push(this.newItem)
this.newItem = ''
}
}
}
}
</script>
删除列表项
为每个列表项添加删除按钮,并通过 splice 方法移除指定项。

<template>
<div>
<input v-model="newItem" placeholder="Add new item">
<button @click="addItem">Add</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
newItem: ''
}
},
methods: {
addItem() {
if (this.newItem.trim() !== '') {
this.items.push(this.newItem)
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
使用计算属性优化
如果需要过滤或处理列表数据,可以使用计算属性。
<template>
<div>
<input v-model="newItem" placeholder="Add new item">
<button @click="addItem">Add</button>
<ul>
<li v-for="(item, index) in filteredItems" :key="index">
{{ item }}
<button @click="removeItem(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3'],
newItem: ''
}
},
computed: {
filteredItems() {
return this.items.filter(item => item.includes('Item'))
}
},
methods: {
addItem() {
if (this.newItem.trim() !== '') {
this.items.push(this.newItem)
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
使用 Vue 3 的 Composition API
在 Vue 3 中,可以使用 ref 和 reactive 来管理状态。
<template>
<div>
<input v-model="newItem" placeholder="Add new item">
<button @click="addItem">Add</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const items = ref(['Item 1', 'Item 2', 'Item 3'])
const newItem = ref('')
const addItem = () => {
if (newItem.value.trim() !== '') {
items.value.push(newItem.value)
newItem.value = ''
}
}
const removeItem = (index) => {
items.value.splice(index, 1)
}
return {
items,
newItem,
addItem,
removeItem
}
}
}
</script>






