微信小程序实现一个todolist这样的小demo

小程序实现todolist

下面是一个简单的待办事项清单应用的示例,它包括添加任务、完成任务和删除任务的功能。

app.json 文件中

{
    
    
  "pages": [
    "pages/index/index",
    "pages/todoList/todoList"
  ],
  "window": {
    
    
    "navigationBarTitleText": "Todo List"
  }
}

创建 pages/todoList/todoList.js 文件

Page({
    
    
  data: {
    
    
    todoList: []
  },
  onLoad: function() {
    
    
    this.loadTodoList();
  },
  loadTodoList: function() {
    
    
    // 从本地存储中加载待办事项列表
    const todoList = wx.getStorageSync('todoList');
    if (todoList) {
    
    
      this.setData({
    
    
        todoList: JSON.parse(todoList)
      });
    }
  },
  addTodo: function(e) {
    
    
    const value = e.detail.value;
    if (value) {
    
    
      const todo = {
    
    
        id: new Date().getTime(),
        content: value,
        completed: false
      };
      const todoList = [...this.data.todoList, todo];
      this.setData({
    
    
        todoList
      });
      wx.setStorageSync('todoList', JSON.stringify(todoList));
    }
  },
  completeTodo: function(e) {
    
    
    const id = e.currentTarget.dataset.id;
    const todoList = this.data.todoList.map(todo => {
    
    
      if (todo.id === id) {
    
    
        todo.completed = true;
      }
      return todo;
    });
    this.setData({
    
    
      todoList
    });
    wx.setStorageSync('todoList', JSON.stringify(todoList));
  },
  deleteTodo: function(e) {
    
    
    const id = e.currentTarget.dataset.id;
    const todoList = this.data.todoList.filter(todo => todo.id !== id);
    this.setData({
    
    
      todoList
    });
    wx.setStorageSync('todoList', JSON.stringify(todoList));
  }
})

创建 pages/todoList/todoList.wxml 文件

<view class="container">
  <view class="header">
    <text>待办事项:</text>
    <input type="text" bindconfirm="addTodo" placeholder="请输入任务内容" />
  </view>
  <view class="list">
    <block wx:for="{
    
    {todoList}}">
      <view class="item {
    
    {item.completed ? 'completed' : ''}}">
        <text>{
    
    {
    
    item.content}}</text>
        <button bindtap="completeTodo" data-id="{
    
    {item.id}}">完成</button>
        <button bindtap="deleteTodo" data-id="{
    
    {item.id}}">删除</button>
      </view>
    </block>
  </view>
</view>

当你输入任务内容并按下回车键时,任务将被添加到待办事项清单中。
点击任务后面的"完成"按钮,任务将被标记为已完成,并在界面上显示为灰色。
点击任务后面的"删除"按钮,任务将从待办事项清单中删除。
这个示例只是一个简单的待办事项清单应用,你可以根据自己的需求进行扩展和修改。

到这里也就结束了,希望对您有所帮助。

猜你喜欢

转载自blog.csdn.net/weixin_71893790/article/details/135153454