<template>
<div>
<h2>{{ title }}</h2>
<el-input v-model="newItem" placeholder="请输入新的列表项" style="width: 200px;"></el-input>
<el-button type="primary" @click="addItem">添加</el-button>
<el-list :data="items">
<template v-slot:default="{ item, index }">
<el-list-item>
{{ item }}
<el-button type="danger" icon="el-icon-delete" @click="removeItem(index)"></el-button>
</el-list-item>
</template>
</el-list>
</div>
</template>
<script>
export default {
props: {
title: String,
items: Array,
},
data() {
return {
newItem: '',
};
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push(this.newItem);
this.newItem = '';
}
},
removeItem(index) {
this.items.splice(index, 1);
},
},
};
</script>
##在这个组件中,我们使用了 Element UI 的 el-input、el-button 和 el-list 组件来替代原来的 input、button 和 ul。我们使用了 v-model 指令将 input 的值与组件的数据属性 newItem 绑定起来。在添加项的方法 addItem 中,我们首先检查 newItem 是否为空或全是空格,如果不是,则将它添加到 items 数组中,并将 newItem 重置为空。在列表项中,我们使用了 el-list 和 el-list-item 组件,并在每一项后面添加了一个带有删除图标的 el-button 组件。
这个组件可以在父组件中像这样使用:
<template>
<div>
<tolist title="Shopping List" :items="shoppingList" />
</div>
</template>
<script>
import Tolist from '@/components/Tolist.vue';
import { ElButton, ElInput, ElList, ElListItem } from 'element-ui';
export default {
components: {
Tolist,
ElButton,
ElInput,
ElList,
ElListItem,
},
data() {
return {
shoppingList: ['Milk', 'Eggs', 'Bread', 'Cheese'],
};
},
};
</script>
在这个示例中,我们首先导入了需要使用的 Element UI 组件,并将它们作为父组件的子组件进行注册。然后我们将一个名为 shoppingList 的数组传递给了 tolist 组件,并指定了列表的标题为 “Shopping List”。我们可以通过表单添加新的列表项,并通过带有垃圾桶图标的 “删除” 按钮删除任何一个列表项。