ES6—項目小練習-TodoList(15)

ES6技術自己很是容易,相信你們也體會到了。各類新特性都不難,可是爲何不少人學習起來困難呢?css

其實ES6難的不是技術,而是實際工做環境的搭建。好比咱們想寫一個簡單的ES6版本的TodoList.html

不少同窗學生是這麼放棄的:前端

經過搜索引擎,發現不少教程都是直接引入Traceur.js 而後講解ES6各類功能和語法的,可是好像實際並非直接引入Traceur.js ,而是用babel。node

使用babel的話好像須要安裝node.js,還有會用npmwebpack

安裝好npm 之後我是該使用gulp仍是webpack呢?web

嗯,應該webpack吧,這個好像目前更主流。好,就選它了。npm

webpack怎麼安裝?是否是須要webpack-cli?另外webpack 4.0好像更好用,可是好像安裝又有兼容性問題?gulp

糾結ing……數組

考慮了半天后,終於下定決心,就用最新版本,學老的沒用。sass

安裝好webpack 4.0,對了是否是要配置工做流?

對配置吧,這纔是「工做的方式」,js須要壓縮,裝個壓縮插件,webpack怎麼用啊?有各類rule,plugins,還有entry.

開始頭疼,耐着性子把網上的教程配置完,這個插件怎麼報錯了啊?

繼續查,原來是webpack 4.0和它不兼容,換webpack 3.0仍是換插件?

糾結半天后,終於鼓起勇氣,換插件!

又配置出錯了……

開始進入暴走模式,又氣又惱。

好吧,折騰半天,請教大牛總算經過了。

那麼問題來了,學了這麼久css和js,我竟然不知道往哪裏寫css……

好吧,據說得用sass……

配置完了,sass語法不會……

我就想寫一個ES6的todoList,太費勁了,咋得學這麼東西啊……

仍是放棄吧,我感受我不適合作前端。

雖然誇張了些,可是大部分前端都有相似的經歷。

圖片描述
今天我就讓你們完全的學會如何工做中寫ES6,咱們依然用todoList舉例,對了咱們並不須要學習webpack,sass,插件等等。咱們只學習ES6,對其它的通通不用學,你會用就能夠,也不過幾個命令而已。

ok,咱們開始。

首先,拿到我配置好的工做流,直接在根目錄下進入命令行,而後

npm install

安裝完成後,使用

npm run dev

而後就能夠用了,

圖片描述
就這幾個文件,對應寫html,js和css。

首先咱們先寫 html文件 。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,
  maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
    <title>TODOList</title>
</head>
<body>
    <div class="container">
        <div class="item-area">
            <h1 class="title">TODO-LIST</h1>
            <ul class="item">
                <li class="item-li-default">輸入任務...</li>
            </ul>
        </div>
        <div class="input-area">
            <form class="add-item">
                <input maxlength="15" type="text" name="item" placeholder="待辦事件..." class="add-text" required>
                <input  type="submit" value="+ 添加" class="add-button">
            </form>
        </div>
    </div>
</body>
</html>

接着,寫css美化一下

* {
    padding: 0;
    margin: 0;
  }
  li {
    list-style: none;
  }
  html {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    min-height: 100vh;
    box-sizing: border-box;
    font-family: Futura, "Trebuchet MS", Arial, sans-serif;
    background: #ffc600;
  }
  svg {
    fill: #fff;
    background: rgba(0,0,0,0.1);
    padding: 20px;
    border-radius: 50%;
    width: 100px;
    margin-bottom: 50px;
  }
  .container {
    padding: 20px;
    max-width: 350px;
    box-shadow: 0 0 0 10px rgba(0,0,0,0.1);
    background: #fff;
  }
  .container .item-area .title {
    text-align: center;
    margin: 10px 0;
    color: #aaa;
    font-weight: 200;
  }
  .container .item-area .item {
    background: #fff;
    border-radius: 4px;
  }
  .container .item-area .item .item-li-default {
    color: #46b7b9;
  }
  .container .item-area .item .item-li {
    width: 100%;
    border-bottom: 1px solid #eee;
    height: 30px;
    line-height: 30px;
    text-align: left;
    color: #f95959;
  }
  .container .item-area .item .item-li .delete-item {
    float: right;
    outline: none;
    width: 44px;
    height: 26px;
    border-radius: 4px;
    color: #f05941;
    background: #fafafa;
  }
  .container .item-area .item .item-li input:checked + .item-text {
    color: #196b69;
    text-decoration: line-through;
  }
  .container .input-area {
    padding-top: 10px;
  }
  .container .input-area .add-text {
    outline: 0;
    border: 1px solid rgba(0,0,0,0.1);
    height: 40px;
    border-radius: 4px;
    text-indent: 10px;
  }
  .container .input-area .add-button {
    outline: 0;
    height: 40px;
    border-radius: 4px;
    width: 60px;
    padding: 4px;
    background-color: #fff;
    border: 1px solid rgba(0,0,0,0.1);
  }

ok,使用

npm satrt

圖片描述
架子搭完了,很簡單,甚至是不須要你寫這些東西,可是你必需要會寫,不過寫這個的意義並不大,由於咱們的重點是學ES6,好咱們直搗黃龍。

import style from "./main.css";

把css引入js文件,你就把它當成link就行。

開始核心部分,

const add = document.querySelector('.add-item');//找到添加事件的變表單,之因此須要監聽form而不是input是由於這樣用戶回車時也會觸發事件
add.addEventListener('submit', addItem);

點擊按鈕,添加一個代辦事件,看看addItem怎麼寫。

//定義一個用來存聽任務的數組
var items = JSON.parse(localStorage.getItem('items')) || [];
function addItem(e){
    e.preventDefault();  //阻止表單提交的默認行爲
    const text = (this.querySelector('[name=item]')).value;
    const item ={
        text,
        done: false
    };
    items.push(item);
    //調用populateList,將items數組中的事件添加到html頁面中
    populateList(items, container);
    localStorage.setItem('items', JSON.stringify(items));
    this.reset();
}

把任務扔到數組裏,而後讓數組去生成列表,最後重置表單。咱們看看待辦事件列表怎麼生成的

//將items數組中的事件添加到html頁面中
const container = document.querySelector('.item');//找到將事項加入的元素
function populateList(plate, plateList) {
    plateList.innerHTML=plate.map( (item, i) => {
        return`
        <li class="item-li">
            <input type="checkbox" data-index=${i} id="item${i}" ${item.done ? 'checked' : ''}>
            <lable class="item-text" for="item${i}">${item.text}</lable>
            <input type="button" value="刪除" class="delete-item" >
        </li>
    `
    }).join('');
}
populateList(items, container);

ok,很是簡單。我看看看如何刪除一個任務。

//刪除事件
function deleteDone(e) {
    const msg ='肯定刪除該項事件?'
    if(!e.target.matches("input[type='button']")) return; // 只有複選框才能夠執行事件
    const el = e.target;
    const index = el.dataset.index;
    if(confirm(msg)){
        items.splice(index,1); //將選中數組刪除
        localStorage.setItem('items', JSON.stringify(items));
        populateList(items, container);
    }else{
        return;
    }
}
container.addEventListener('click', deleteDone);

其實最關鍵的就一句話,

items.splice(index,1); //將選中數組刪除

玩的就是數組,這個例子雖然簡單用的倒是MVC的思想。

接下來咱們再看看切換任務狀態,

//切換checked狀態
function toggleDone(e) {
    if(!e.target.matches("input[type='checkbox']")) return; // 只有複選框才能夠執行事件
    const el = e.target;
    const index = el.dataset.index;
    items[index].done =!items[index].done;
    localStorage.setItem('items', JSON.stringify(items));
    populateList(items, container);
}
container.addEventListener('click', toggleDone);

咱們結合着本地存儲的數據結構看,這樣就更好理解。

圖片描述

切換狀態其實就是對應的數組值取反。

好了,到如今爲止,咱們看看總體代碼:

完整代碼以下:

import style from "./main.css";
const add = document.querySelector('.add-item');//找到添加事件的變表單,之因此須要監聽form而不是input是由於這樣用戶回車時也會觸發事件
const container = document.querySelector('.item');//找到將事項加入的元素
var items = JSON.parse(localStorage.getItem('items')) || [];

//        將添加的待辦事件push進items數組中
function addItem(e){
    e.preventDefault();  //阻止表單提交的默認行爲
    const text = (this.querySelector('[name=item]')).value;
    const item ={
        text,
        done: false
    };
    items.push(item);
    populateList(items, container);
    localStorage.setItem('items', JSON.stringify(items));
    this.reset();
}

//      將items數組中的事件添加到html頁面中
function populateList(plate, plateList) {
    plateList.innerHTML=plate.map( (item, i) => {
        return`
        <li class="item-li">
            <input type="checkbox" data-index=${i} id="item${i}" ${item.done ? 'checked' : ''}>
            <lable class="item-text" for="item${i}">${item.text}</lable>
            <input type="button" value="刪除" class="delete-item" >
        </li>
    `
    }).join('');
}

//        切換checked狀態
function toggleDone(e) {
    if(!e.target.matches("input[type='checkbox']")) return; // 只有複選框才能夠執行事件
    const el = e.target;
    const index = el.dataset.index;
    items[index].done =!items[index].done;
    localStorage.setItem('items', JSON.stringify(items));
    populateList(items, container);
}

//        刪除事件
function deleteDone(e) {
    const msg ='肯定刪除該項事件?'
    if(!e.target.matches("input[type='button']")) return; // 只有複選框才能夠執行事件
    const el = e.target;
    const index = el.dataset.index;
    if(confirm(msg)){
        items.splice(index,1); //將選中數組刪除
        localStorage.setItem('items', JSON.stringify(items));
        populateList(items, container);
    }else{
        return;
    }
}

add.addEventListener('submit', addItem);
container.addEventListener('click', toggleDone);
container.addEventListener('click', deleteDone);

populateList(items, container);

寫完了上線

npm run build

好,咱們總結一下:

1.不要陷入到開發環境裏,咱們是學習ES6,而不是webpack,因此直接用我寫的webpack工做流就好。

2.要會寫這個項目的html和css,注意實際項目中css的引入方式。

3.學習mvc的思想,嘗試使用經過修改數組的方式實現任務的增長、刪除和修改功能。

4.掌握本地存儲的用法。

好,本文就到這裏,下節課咱們再作一個更貼近工做的例子。

相關文章
相關標籤/搜索