vue + element-ui 简单的入门小例子——todolist

这里写图片描述
1. 这里不使用vue-cli来构建,而是直接创建一个html,IE不支持
2. 引入Vue和element-ui,注意vue要先于element-ui的js引入,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <!-- import Vue before Element -->
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <!-- import JavaScript -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <title>todolist</title>
</head>
<div id="app">
  <!-- element的input组件 -->
  <el-input></el-input>
</div>
<body>
<script>
  new Vue({ //记得声明,不然看不到element的input组件
    el: '#app',
    data: {
    },
    methods: {//这里用于定义方法
    },
    computed: {//计算属性
    }
  })
</script>
</body>
</html>

只要引入 js 和 css 成功,打开页面可以看到如下
这里写图片描述

接下来用HTML,一个输入框,一行字显示完成和未完成的事项数量,和事项列表,然后添加几个简单的方法

<body>
  <div id="app">
    <el-container>
      <el-header height="20">
        <h1>ToDoList</h1>
      </el-header>
      <el-main>
        <el-input placeholder="回车添加待办事项" class="todoinput" @keyup.enter.native="add" v-model="newtodo.content"></el-input>
        <p>进行中:{{ todolist.length }} 已完成:{{ donenum }}</p>
        <el-row v-for="(item, index) in todolist" class="list-row">
          <el-col :xs="2" :sm="1" :md="1" :lg="1" :xl="1" class="check" :class="{ red: !todolist[index].done, 'green': todolist[index].done }">
            <el-checkbox size="mini" v-model="item.done"></el-checkbox>
          </el-col>
          <el-col :xs="20" :sm="22" :md="22" :lg="22" :xl="22">
            <input type="text" v-model="item.content" class="ipcont" :class="{done: todolist[index].done}">
          </el-col>
          <el-col :xs="2" :sm="1" :md="1" :lg="1" :xl="1" class="close">
            <i class="el-icon-close" @click="del(index)"></i>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
  <script>
    var doit = new Vue({
      el: '#app',
      data: {
        newtodo: {
          content: '',
          done: false
        },
        todolist: [
          {
            content: '现在开始吧',
            done: false
          }
        ]
      },
      methods: {
        add: function () {
          if (this.newtodo.content) {
            this.todolist.push(this.newtodo)
            this.newtodo = { content: '', done: false }
          }
        },
        del: function (index) {
          this.todolist.splice(index, 1)
        }
      },
      computed: {
        donenum: function () {
          return this.todolist.filter(function (val) { return val.done }).length
        }
      }
    })
  </script>

接下来解释一下代码:

<!--input回车触发add函数,添加.native是因为element-ui对input有封装,不添加无法触发-->
@keyup.enter.native="add

<!--v-model="newtodo.content,双向绑定,输入的内容-->
。。 v-model="newtodo.content"

用浏览器查看页面代码可见,我们绑定的 class=”todoinput是在input的外部。

这里写图片描述

<!--循环data里todolist的内容 item是每一项的内容, index是索引-->
 v-for="(item, index) in todolist" 

<!--通过done的值来绑定class,当done是true时绑定green表示完成,false时绑定red这个class-->
:class="{ red: !todolist[index].done, 'green': todolist[index].done }

<!--双向绑定checkbox,item.done的值判断是否选中-->
<el-checkbox size="mini" v-model="item.done"></el-checkbox>

<!--给input绑定一个删除线的class,当done为true表示完成时就添加这个class-->
<input type="text" v-model="item.content" class="ipcont" :class="{done: todolist[index].done}">

<!--点击出发删除函数,会把index传给自己定义del函数,-->
<i class="el-icon-close" @click="del(index)"></i>

//if判断输入内容是否为空,不为空就把输入的内容添加到todolist
//添加后把input的内容复位
add: function () {
          if (this.newtodo.content) {
            this.todolist.push(this.newtodo)
            this.newtodo = { content: '', done: false }
          }
        },
//这里很好理解,点击就删除,用的是原生js的splice()
del: function (index) {
          this.todolist.splice(index, 1)
        }

//计算属性,filter()把,done为true的返回出来,然后用length得出为true的一共有几个
//在HTML部分的 “已完成:{{ donenum }}” 把已完成的显示到页面上
donenum: function () {
          return this.todolist.filter(function (val) { return val.done }).length
        }

接下来是样式,很简单,不做解释

  <style>
    /*#FBFBFB #B9E1DC #F38181 #756C83 */

    #app {
      font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
      color: #756C83;
    }

    .el-header {
      text-align: center;
    }

    .todoinput {
      margin-bottom: 40px;
    }

    .list-row {
      height: 40px;
      background-color: #fbfbfb;
      margin-bottom: 5px;
    }

    .check {
      text-align: center;
      line-height: 40px;
    }

    .red {
      border-left: #ef5f65 2px solid;
    }

    .green {
      border-left: #B9E1DC 2px solid;
    }

    .ipcont {
      width: 90%;
      margin-top: 8px;
      border: 0;
      line-height: 24px;
      background-color: transparent;
      font-size: 16px;
      color: #756C83;
    }

    .close {
      text-align: center;
      line-height: 40px;
    }

    .el-icon-close {
      cursor: pointer;
    }

    .el-icon-close:hover {
      color: #ef5f65;
    }

    .done {
      text-decoration: line-through;
    }
  </style>

如果本地存储,可以用HTML的localStorage来存储,在script变迁内添加如下代码

var STORAGE_KEY = 'todolist'

      function fetch() {
        return JSON.parse(window.localStorage.getItem(STORAGE_KEY)
          || '[]')
      }
      function save(items) {
        window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
      }

再通过watch来监听todolist的变化,一旦变化就通过save()保存,每次进入时通过fetch()读取
完整代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <!-- import Vue before Element -->
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <!-- import JavaScript -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <title>todolist</title>
</head>

<body>
  <div id="app">
    <el-container>
      <el-header height="20">
        <h1>ToDoList</h1>
      </el-header>
      <el-main>
        <el-input placeholder="回车添加待办事项" class="todoinput" @keyup.enter.native="add" v-model="newtodo.content"></el-input>
        <p>进行中:{{ todolist.length }} 已完成:{{ donenum }}</p>
        <el-row v-for="(item, index) in todolist" class="list-row">
          <el-col :xs="2" :sm="1" :md="1" :lg="1" :xl="1" class="check" :class="{ red: !todolist[index].done, 'green': todolist[index].done }">
            <el-checkbox size="mini" v-model="item.done"></el-checkbox>
          </el-col>
          <el-col :xs="20" :sm="22" :md="22" :lg="22" :xl="22">
            <input type="text" v-model="item.content" class="ipcont" :class="{done: todolist[index].done}">
          </el-col>
          <el-col :xs="2" :sm="1" :md="1" :lg="1" :xl="1" class="close">
            <i class="el-icon-close" @click="del(index)"></i>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
  <script>
    var STORAGE_KEY = 'todolist'

      function fetch() {
        return JSON.parse(window.localStorage.getItem(STORAGE_KEY)
          || '[]')
      }
      function save(items) {
        window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
      }

//--------------------------------------------------
    var doit = new Vue({
      el: '#app',
      data: {
        newtodo: {
          content: '',
          done: false
        },
        todolist: fetch()
      },
      methods: {
        add: function () {
          if (this.newtodo.content) {
            this.todolist.push(this.newtodo)
            this.newtodo = { content: '', done: false }
          }
        },
        del: function (index) {
          this.todolist.splice(index, 1)
        }
      },
      computed: {
        donenum: function () {
          return this.todolist.filter(function (val) { return val.done }).length
        }
      },
      watch: {
        todolist: {
        handler(items) {
          save(items)
        },
        deep: true
      }
      }
    })
  </script>
  <style>
    /*#FBFBFB #B9E1DC   #F38181  #756C83 */

    #app {
      font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
      color: #756C83;
    }

    .el-header {
      text-align: center;
    }

    .todoinput {
      margin-bottom: 40px;
    }

    .list-row {
      height: 40px;
      background-color: #fbfbfb;
      margin-bottom: 5px;
    }

    .check {
      text-align: center;
      line-height: 40px;
    }

    .red {
      border-left: #ef5f65 2px solid;
    }

    .green {
      border-left: #B9E1DC 2px solid;
    }

    .ipcont {
      width: 90%;
      margin-top: 8px;
      border: 0;
      line-height: 24px;
      background-color: transparent;
      font-size: 16px;
      color: #756C83;
    }

    .close {
      text-align: center;
      line-height: 40px;
    }

    .el-icon-close {
      cursor: pointer;
    }

    .el-icon-close:hover {
      color: #ef5f65;
    }

    .done {
      text-decoration: line-through;
    }
  </style>
</body>

</html>

就这么多了。
可以点这里看看效果

  • 12
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
好的,下面是一个使用React和TypeScript完成的TodoList示例: 首先,创建一个React组件:TodoList.tsx ```tsx import React, { useState } from "react"; interface TodoItem { id: number; content: string; completed: boolean; } const TodoList = () => { const [todos, setTodos] = useState<TodoItem[]>([]); const [inputValue, setInputValue] = useState(""); const handleAddTodo = () => { if (inputValue.trim() === "") return; const newTodo: TodoItem = { id: todos.length, content: inputValue, completed: false }; setTodos([...todos, newTodo]); setInputValue(""); }; const handleToggleTodo = (id: number) => { const updatedTodos = todos.map(todo => todo.id === id ? { ...todo, completed: !todo.completed } : todo ); setTodos(updatedTodos); }; const handleDeleteTodo = (id: number) => { const updatedTodos = todos.filter(todo => todo.id !== id); setTodos(updatedTodos); }; return ( <div> <h1>Todo List</h1> <div> <input type="text" value={inputValue} onChange={e => setInputValue(e.target.value)} /> <button onClick={handleAddTodo}>Add</button> </div> <ul> {todos.map(todo => ( <li key={todo.id} style={{ textDecoration: todo.completed ? "line-through" : "none" }} > {todo.content} <button onClick={() => handleToggleTodo(todo.id)}> {todo.completed ? "Uncomplete" : "Complete"} </button> <button onClick={() => handleDeleteTodo(todo.id)}>Delete</button> </li> ))} </ul> </div> ); }; export default TodoList; ``` 在这个组件中,我们定义了一个状态todos来存储所有的待办事项,以及一个状态inputValue来存储用户输入的新待办事项的内容。我们通过useState Hook来定义这些状态。 我们还定义了三个处理函数handleAddTodo、handleToggleTodo和handleDeleteTodo来添加、切换完成状态和删除待办事项。我们通过map函数来遍历todos数组,以便将每个待办事项渲染为一个li元素。 最后,我们导出TodoList组件。 接下来,在App.tsx中使用TodoList组件: ```tsx import React from "react"; import TodoList from "./TodoList"; const App = () => { return ( <div> <TodoList /> </div> ); }; export default App; ``` 现在,我们就可以在浏览器中查看TodoList应用程序了。 注:在使用前需要先安装React和TypeScript的依赖。在终端中执行以下命令: ```sh npm install react react-dom npm install --save-dev typescript @types/react @types/react-dom ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值