Vue

前端框架、資料綁定

tags: summertrain

安裝 vue-cli

npm install -g @vue/cli
# OR
yarn global add @vue/cli

創建專案

vue create todo-list

選擇 CSS Pre-Processer(toggle with space)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


使用 pug

npm i vue-cli-plugin-pug
# OR
yarn add vue-cli-plugin-pug

開啟網站

cd todo-list
npm run serve --port <port> --host <host>
# OR
yarn serve --port <port> --host <host>

打開 http://<host>:<port>

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


檔案結構

.
├── README.md
├── babel.config.js  # Preprocesser 設定
├── node_modules     # 安裝的模組
├── package.json     # 模組設定
├── public           # index.html 以及直接被存取的檔案
└── src              # source code

開始寫 Vue!

cd src/
vi App.vue

Data binding

{{ somedata }}

<template lang="pug"> #app ul li {{ todo }} </template> <script> export default { data(){return{ todo: '吃飯' }} } </script>

Two-way Data bindings

v-model='somedata'

<template lang="pug"> #app input(type="text" placeholder="輸入待辦事項" v-model="todo.content") ul li input(type="checkbox" v-model="todo.completed") | {{ todo.content }} </template> <script> export default { data(){return{ todo: { content: '睡覺', completed: false, } }} } </script>

Event Handling

v-on:someEvent='someMethod()'

input(type="text" placeholder="輸入待辦事項" v-model="newTodo" v-on:keyup.enter="addTodo(newTodo)") ul li input(type="checkbox" v-model="todo.completed") | {{ todo.content }}
data(){return{ newTodo: '', todo: { content: '睡覺', completed: false, } }},
methods:{ addTodo(newTodo){ this.todo = {content: newTodo, completed: false} }, }

List Rendering

v-for='item in items'

li(v-for='todo in todos') input(type="checkbox" v-model="todo.completed") | {{ todo.content }} - a(v-on:click="removeTodo(todo)") 刪除
todos: []
methods:{ addTodo(newTodo){ this.todos.push({content: newTodo, completed: false}) }, removeTodo(todo){ this.todos.splice(this.todos.indexOf(todo), 1); } }

Class and Style Bindings

v-bind:class='{}'

li(v-bind:class='{ strikethrough: todo.completed }' v-for='todo in todos')
<style lang='sass'> .strikethrough text-decoration: line-through </style>

練習

  1. 按下 enter 時 input 清空
  2. 清空全部完成的事項