vue实现添加内容代码
以下是一个基于 Vue.js 实现添加内容的代码示例,包含核心逻辑和关键步骤:
基础实现
模板部分(Template)
<template>
<div>
<input v-model="newItem" placeholder="输入内容" @keyup.enter="addItem">
<button @click="addItem">添加</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">删除</button>
</li>
</ul>
</div>
</template>
脚本部分(Script)
<script>
export default {
data() {
return {
newItem: '',
items: []
}
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push(this.newItem)
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
进阶优化
添加数据验证
methods: {
addItem() {
if (!this.newItem.trim()) {
alert('内容不能为空')
return
}
this.items.push(this.newItem.trim())
this.newItem = ''
}
}
使用计算属性
computed: {
itemCount() {
return this.items.length
}
}
完整组件示例
<template>
<div class="item-manager">
<div class="input-group">
<input
v-model="newItem"
placeholder="输入新内容"
@keyup.enter="handleAdd"
class="input-field"
>
<button @click="handleAdd" class="add-btn">添加</button>
</div>
<div v-if="items.length > 0" class="item-list">
<div v-for="(item, index) in items" :key="index" class="item">
<span>{{ item }}</span>
<button @click="handleRemove(index)" class="remove-btn">×</button>
</div>
</div>
<p v-else class="empty-tip">暂无内容,请添加</p>
</div>
</template>
<script>
export default {
data() {
return {
newItem: '',
items: []
}
},
methods: {
handleAdd() {
const content = this.newItem.trim()
if (!content) return
this.items.push(content)
this.newItem = ''
},
handleRemove(index) {
this.items.splice(index, 1)
}
}
}
</script>
<style scoped>
.item-manager {
max-width: 500px;
margin: 0 auto;
}
.input-group {
display: flex;
margin-bottom: 20px;
}
.input-field {
flex: 1;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
.add-btn {
margin-left: 10px;
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.item-list {
border: 1px solid #eee;
border-radius: 4px;
}
.item {
display: flex;
justify-content: space-between;
padding: 10px;
border-bottom: 1px solid #eee;
}
.item:last-child {
border-bottom: none;
}
.remove-btn {
background: none;
border: none;
color: #ff6b6b;
cursor: pointer;
font-size: 16px;
}
.empty-tip {
color: #999;
text-align: center;
padding: 20px;
}
</style>
关键点说明
- 使用
v-model实现双向数据绑定 - 通过
@keyup.enter监听回车事件 - 使用数组的
push方法添加新项 - 使用
splice方法删除指定项 - 添加了基本的样式美化
- 包含空状态提示
可以根据实际需求进一步扩展功能,如添加本地存储、服务端交互等。







