vue实现一个todolist组件

该组件展示了如何利用ElementUI的el-input、el-button和el-list创建一个todolist,通过v-model实现数据双向绑定,添加和删除列表项功能。在父组件中导入并使用组件,可以方便地管理列表数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

todolist组件

<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”。我们可以通过表单添加新的列表项,并通过带有垃圾桶图标的 “删除” 按钮删除任何一个列表项。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值