使用 Vue.js 2 創(chuàng)建 Todo App

All the code for this post can be found on Github.

Vue is a simple and minimal progressive JavaScript framework that can be used to build powerful web applications incrementally.

Vue is a lightweight alternative to other JavaScript frameworks like AngularJS. With an intermediate understanding of HTML, CSS and JS, you should be ready to get up and running with Vue.

Prepare

We'll need the Vue CLI to get started. The CLI provides a means of rapidly scaffolding Single Page Applications and in no time you will have an app running with hot-reload and production-ready builds.

Vue CLI offers a zero-configuration development tool for jumpstarting your Vue apps and component.

A lot of the decisons you have to make regarding how your app scales in future are taken care of. The Vue CLI comes with an array of templates that provide a self-sufficient, out-of-the-box ready to use package. The currently available templates are:

webpack - A full-featured Webpack + Vue-loader setup with hot reload, linting, testing & CSS extraction.

webpack-simple - A simple Webpack + Vue-loader setup for quick prototyping.

browserify - A full-featured Browserify + vueify setup with hot-reload, linting & unit testing.

browserify-simple - A simple Browserify + vueify setup for quick prototyping.

simple - The simplest possible Vue setup in a single HTML file

Simply put, the Vue CLI is the fastest way to get your apps up and running.

# install vue-cli
$ npm install --global vue-cli
Creating A Vue 2 Application

Next, we'll set up our Vue app with the CLI.

# create a new project using the "webpack" template
$ vue init webpack todo-app

# install dependencies and go!
$ cd todo-app
$ npm install
$ npm run dev

To style our application we will use Semantic and SweetAlert. Add the minified JavaScript and CSS scripts and links to your index.html file.

<link  rel="stylesheet">
<link  rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/semantic-ui/2.2.10/semantic.min.js"></script>
<script src="https://cdn.bootcss.com/sweetalert/1.1.3/sweetalert.min.js"></script>
Component structure

Every Vue app, needs to have a top level component that serves as the framework for the entire application. Fo our application, we will have a main component and nested within shall be a TodoList Component. Within this there will be todo sub-components.

Main App Component

Let's dive into building our application. First, we'll start with the main top level component. The Vue CLI already generates a main component that can be found in src/App.vue. We will build out the other necessary components.

Creating a Component

The Vue CLI creates a component Hello during set up that can be found in src/components/Hello.vue. We will create our own component called TodoList.vue and won't be needing this anymore.
Inside of the new TodoList.vue file, write the following:

<template>
</template>

<script>
    export default {}
</script>

<style>
</style>

A component file consists three parts: template, script and style. The template area is the visual part of a component. Behaviour, events and data storage for the template are handled by the script. The style serves to further improve the appearance of the template.

Importing Components

To utilize the component we just created, we need to import it in our main component. Inside of src/App.vue make the following changes:

// add this line
import TodoList from './components/TodoList'  
// remove this line
import Hello from './components/Hello'  

We will also need to reference the TodoList component in the components property and delete the previous reference to Hello Component. After the changes, our script should look like this.

<script>
    import TodoList from './components/TodoList'

    export default {
        components: {
            // Add a reference to the TodoList component in the components property
            TodoList
        }
    }
</script>

To render the component, we invoke it like an HTML element.

<template>
    <div>
        <TodoList></TodoList>
    </div>
</template>
Adding Component Data

We will need to supply data to the main component that will be used to display the list of todos. Our todos will have three properties: The title, project and done(to indicate if the todo is complete or not). Components avail data to their respective templates using a data function. This function returns an object with the properties intended for the template. Let's add some data to our component.

export default {
    components: {
        TodoList
    },
    // data function avails data to the template
    data() {
        return {
            todos: [{
                title: 'Todo A',
                project: 'Project A',
                done: false,
            }, {
                title: 'Todo B',
                project: 'Project B',
                done: true,
            }, {
                title: 'Todo C',
                project: 'Project C',
                done: false,
            }]
        }
    }
}

We will need to pass data from the main component to the TodoList component. For this, we will use the v-bind directive. The directive takes an argument which is indicated by a colon after the directive name. Our argument will be todos which tells the v-bind directive to bind the element’s todos attribute to the value of the expression todos.

<TodoList :todos="todos"></TodoList>

The todos will now be available in the TodoList component as todos. We will have to modify our TodoList component to access this data. The TodoList component has to declare the properties it will accept when using it.

export default {  
    props: ['todos'],
}
Looping and Rendering Data

Inside our TodoList template lets loop over the list of Todos and also show the the number of completed and uncompleted tasks. To render a list of items, we use the v-for directive. The syntax for doing this is represented as v-for="item in items" where items is the array with our data and item is a representation of the array element being iterated on.

<template>
    <div>
        <!--JavaScript expressions in Vue are enclosed in double curly brackets.-->
        <p>Completed Tasks: {{todos.filter(todo => {return todo.done === true}).length}}</p>
        <p>Pending Tasks: {{todos.filter(todo => {return todo.done === false}).length}}</p>
        <div class='ui centered card' v-for="todo in todos">
            <div class='content'>
                <div class='header'>
                    {{ todo.title }}
                </div>
                <div class='meta'>
                    {{ todo.project }}
                </div>
                <div class='extra content'>
                    <span class='right floated edit icon'>
                        <i class='edit icon'></i>
                    </span>
                </div>
            </div>
            <div class='ui bottom attached green basic button' v-show="todo.done">
                Completed
            </div>
            <div class='ui bottom attached red basic button' v-show="!todo.done">
                Pending
            </div>
        </div>
    </div>    
</template>
<script>
    export default {
        props: ['todos'],
    }
</script>
Editing a Todo

Let's extract the todo template into it's own component for cleaner code. Create a new component file Todo.vue in src/components and transfer the todo template. Our file should now look like this:

<template>
    <div class='ui centered card'>
        <div class="content" v-show="!isEditing">
            <div class='header'>
                {{ todo.title }}
            </div>
            <div class='meta'>
                {{ todo.project }}
            </div>
            <div class='extra content'>
                <span class='right floated edit icon item' @click="isEditing=true">
                    <i class='edit link icon'></i>
                </span>
            </div>
        </div>
        <div class='ui bottom attached green basic button' v-show="!isEditing && todo.done" disabled>
            Completed
        </div>
        <div class='ui bottom attached red basic button' v-show="!isEditing && !todo.done" @click="completeTodo(todo)">
            Pending
        </div>
    </div>
</template>
</template>
<script>
    export default {
        props: ['todo'],

    }
</script>

In the TodoList component refactor the code to render the Todo component. We will also need to change the way our todos are passed to the Todo component. We can use the v-for attribute on any components we create just like we would in any other element. The syntax will be like this: <my-component v-for="item in items" :key="item.id"></my-component>. Note that from 2.2.0 and above, a key is required when using v-for with components. An important thing to note is that this does not automatically pass the data to the component since components have their own isolated scopes. To pass the data, we have to use props.

<my-component v-for="(item, index) in items" v-bind:item="item"  v-bind:index="index">
</my-component>

Our refactored TodoList component template:

<template>
    <div>
    
        <p class="tasks">Completed Tasks: {{todos.filter(todo => {return todo.done === true}).length}}</p>
    
        <p class="tasks">Pending Tasks: {{todos.filter(todo => {return todo.done === false}).length}}</p>
    
        <!--we are now passing the data to the todo component to render the todo list-->

        <Todo v-for="(todo, index) in todos" :todo="todo" :key="index"></Todo>
    </div>
</template>

<script>
    import Todo from './Todo'

    export default {
        props: ['todos'],
        components: {
            Todo
        }
    }
</script>

<style>
    .tasks {
        text-align: center;
    }
</style>

Let's add a property to the Todo component class called isEditing. This will be used to dertermine whether the Todo is in edit mode or not. We will have an event handler on the Edit span in the template. This will trigger the showForm method when it gets clicked. This will set the isEditing property to true. Before we take a look at that, we will add a form and set conditionals to show the todo or the edit form depending on whether isEditing property is true or false. Our file should now look like this.

<template>
    <div class='ui centered card'>
        <!--Todo shown when we are not in editing mode.-->
        <div class="content" v-show="!isEditing">
            <div class='header'>
                {{ todo.title }}
            </div>
            <div class='meta'>
                {{ todo.project }}
            </div>
            <div class='extra content'>
                <span class='right floated edit icon item' @click="isEditing=true">
                    <i class='edit link icon'></i>
                </span>
            </div>
        </div>
        <!--form is visible when we are in editing mode-->
        <div class="content" v-show="isEditing">
            <div class='ui form'>
                <div class='field'>
                    <label>Title</label>
                    <input type='text' v-model="todo.title">
                </div>
                <div class='field'>
                    <label>Project</label>
                    <input type='text' v-model="todo.project">
                </div>
                <div class='ui two button attached buttons'>
                    <button class='ui basic blue button' @click="isEditing=false">
                        Close
                    </button>
                </div>
            </div>
        </div>
        <div class='ui bottom attached green basic button' v-show="!isEditing && todo.done" disabled>
            Completed
        </div>
        <div class='ui bottom attached red basic button' v-show="!isEditing && !todo.done">
            Pending
        </div>
    </div>
</template>
</template>
<script>
export default {
    data() {
        return {
            isEditing: false
        }
    },
    props: ['todo']

}
</script>
Deleting a Todo

Let's begin by adding an icon to delete a Todo just below the edit icon.

<template>
    <span class='right floated edit icon' v-on:click="isEditing=true">
        <i class='edit link icon'></i>
    </span>
    <!-- add the trash icon in below the edit icon in the template -->
    <span class='right floated trash icon' v-on:click="deleteTodo(todo)">
        <i class='trash link icon'></i>
    </span>
</template>

Next, we'll add a method to handle the icon click. This method will emit an event delete-todo to the parent TodoList Component and pass the current Todo to delete. We will add an event listener to delete icon.

// Todo component
methods:{
    deleteTodo(todo){
        this.$emit('delete-todo', todo)
    }
}

The parent component(TodoList) will need an event handler to handle the delete. Let's define it.

// TodoList component
methods:{
    deleteTodo(todo){
        swal({
            title: "Are you sure?",
            text: "This To-Do will be permanently deleted!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
            },
            () => {
                const todoIndex = this.todos.indexOf(todo)
                this.todos.splice(todoIndex, 1)
                swal("Deleted!", "Your To-Do has been deleted.", "success")
            });
    }
}

The deleteTodo method will be passed to the Todo component as follows.

<!-- TodoList template -->
<Todo v-for="(todo, index) in todos" :todo="todo" :key="index" @delete-todo="deleteTodo"></Todo>

Once we click on the delete icon, an event will be emitted and propagated to the parent component which will then delete it.

Adding A New Todo

To create a new todo, we'll start by creating a new component CreateTodo.vue in src/components. This will display a button with a plus sign that will turn into a form when clicked. It should look something like this.

<template>
    <div class='ui basic content center aligned segment'>
        <button class='ui basic button icon' @click="isCreating=true" v-show="!isCreating">
            <i class='plus icon'></i>
        </button>
        <div class='ui centered card' v-show="isCreating">
            <div class='content'>
                <div class='ui form'>
                    <div class='field'>
                        <label>Title</label>
                        <input type='text' v-model="titleText">
                    </div>
                    <div class='field'>
                        <label>Project</label>
                        <input type='text' v-model="projectText">
                    </div>
                    <div class="ui buttons">
                        <button class="ui positive button" @click="sendForm">Create</button>
                        <div class="or"></div>
                        <button class="ui button" @click="isCreating=false">Cancel</button>   
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            titleText: '',
            projectText: '',
            isCreating: false,
        }
    },
    methods: {
        sendForm() {
            const title = this.titleText;
            const project = this.projectText;
            if (title.length > 0 && project.length > 0) {
                this.$emit('add-todo', {title, project, done: false})
                this.titleText = ''
                this.projectText = ''
            }
            this.isCreating = false
        }
    }
};
</script>

After creating the new component, we import it and add it to the components property.

// Main Component App.vue
import CreateTodo from './components/CreateTodo'

export default {
    components: {
        TodoList,
        CreateTodo
    }
}

We'll also add a method for creating new Todos.

// App.vue
methods:{
    addTodo(todo){
        this.todos.push(todo)
        swal("Success!", "To-Do created!", "success")
    }
}

The CreateTodo component will be invoked in the App.vue template as follows:

<CreateTodo @add-todo="addTodo"></CreateTodo>
Completing A Todo

Finally, we'll add a method completeTodo to the Todo Component that emits an event complete-todo to the parent component when the pending button is clicked and sets the done status of the todo to true.

// Todo component
methods:{
    completeTodo(todo) {
        this.$emit('complete-todo', todo);
    }
}

An event handler will be added to the TodoList component process the event.

// TodoList component
methods:{
    completeTodo(todo) {
        const todoIndex = this.todos.indexOf(todo)
        this.todos[todoIndex].done = true
        swal("Success!", "To-Do completed!", "success")
    }
}

To pass the TodoList method to the Todo component we will add it to the Todo component invokation.

<Todo v-for="(todo, index) in todos" :todo="todo" :key="index" @delete-todo="deleteTodo" @complete-todo="completeTodo"></Todo>
Conclusion

We have learned how to initialize a Vue app using the Vue CLI. In addition, we learned about component structure, adding data to components, event listeners and event handlers. We saw how to create a todo, edit it and delete it.

Screenshot
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子裆悄,更是在濱河造成了極大的恐慌摊求,老刑警劉巖隙轻,帶你破解...
    沈念sama閱讀 211,290評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件庞钢,死亡現(xiàn)場(chǎng)離奇詭異访锻,居然都是意外死亡褪尝,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門朗若,熙熙樓的掌柜王于貴愁眉苦臉地迎上來恼五,“玉大人,你說我怎么就攤上這事哭懈≡致” “怎么了?”我有些...
    開封第一講書人閱讀 156,872評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵遣总,是天一觀的道長(zhǎng)睬罗。 經(jīng)常有香客問我轨功,道長(zhǎng),這世上最難降的妖魔是什么容达? 我笑而不...
    開封第一講書人閱讀 56,415評(píng)論 1 283
  • 正文 為了忘掉前任古涧,我火速辦了婚禮,結(jié)果婚禮上花盐,老公的妹妹穿的比我還像新娘羡滑。我一直安慰自己,他們只是感情好算芯,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評(píng)論 6 385
  • 文/花漫 我一把揭開白布柒昏。 她就那樣靜靜地躺著,像睡著了一般熙揍。 火紅的嫁衣襯著肌膚如雪职祷。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,784評(píng)論 1 290
  • 那天届囚,我揣著相機(jī)與錄音有梆,去河邊找鬼。 笑死意系,一個(gè)胖子當(dāng)著我的面吹牛泥耀,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蛔添,決...
    沈念sama閱讀 38,927評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼爆袍,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了作郭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,691評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤弦疮,失蹤者是張志新(化名)和其女友劉穎夹攒,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體胁塞,經(jīng)...
    沈念sama閱讀 44,137評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡咏尝,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評(píng)論 2 326
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了啸罢。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片编检。...
    茶點(diǎn)故事閱讀 38,622評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖扰才,靈堂內(nèi)的尸體忽然破棺而出允懂,到底是詐尸還是另有隱情,我是刑警寧澤衩匣,帶...
    沈念sama閱讀 34,289評(píng)論 4 329
  • 正文 年R本政府宣布蕾总,位于F島的核電站粥航,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏生百。R本人自食惡果不足惜递雀,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評(píng)論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蚀浆。 院中可真熱鬧缀程,春花似錦、人聲如沸市俊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽秕衙。三九已至蠢甲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間据忘,已是汗流浹背鹦牛。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留勇吊,地道東北人曼追。 一個(gè)月前我還...
    沈念sama閱讀 46,316評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像汉规,于是被迫代替她去往敵國(guó)和親礼殊。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容