续前一篇的例子:
分段进行:
var app = new Vue({
el: "#app",,
data(){ // 定义资料
},
created(){ // 初始完成 Vue 建立後要执行...
},
methods:{ // 定义在Vue或页面中要使用的方法(function)
},
computed:{ // 进行计算的方法
}
})
定义初始资料
data() {
return {
todos: [],
visibilityList: [ // 3种检视清单(Tab)
{ name: "全部", value: "all" },
{ name: "进行中", value: "active" },
{ name: "已完成", value: "completed" }
// name是页面显示文字,value是程序中操控的值
],
visibility: 'all', // 当前检视中的清单Tab,预设为全部
cacheTodo: {}, // 暂存的Todo
cacheTitle: '' //暂存的项目名称
}
}
将 API 网址存成一变数
var urlAPI = "https://eudora-hsj.github.io/Vue-practice/data/todolist.json"
并且观察一下 JSON 档资料结构:
{
"data":
[
{
"id": "1",
"title": "买牛奶",
"completed": false
},
{
...
}
]
}
在 methods 里定义读取资料的 function(Axios)
methods:{
getList(url) {
axios
.get(url)
.then((res) => {
this.todos = res.data.data
})
.catch((err) => {
console.log(err)
})
},
}
并且在 Vue 初始建立完成时执行 getList(url)
this.getList(urlAPI)
<button class="btn btn-primary" type="button" @click="addTodo">新增</button>
<input class="form-control" type="text"
v-model="newTodo" @keyup.enter="addTodo"/>
methods: {
addTodo() {
let newTodoStr = this.newTodo.trim()
if (!newTodoStr) {
return
}
this.newTodo = ""
let submitData = {
id: Math.floor(Date.now()),
title: newTodoStr,
completed: false
}
this.todos.push(submitData)
}
}
<li class="list-group-item" :key="item.id" @dblclick="editTodo(item)">
(略)
</li>
methods: {
editTodo(item) {
this.cacheTodo = item
this.cacheTitle = item.title
}
}
<button class="close" type="button" @click="removeTodo(item)">
</button>
methods: {
removeTodo(item) {
this.todos.splice(this.getIndex(item.id), 1)
}
}
<a href="#" @click="cleanTodo">清除所有任务</a>
methods: {
cleanTodo() {
this.todos.splice(0, this.todos.length)
}
}
}
Tab 页签内容抓取自 data 里的 visibilityList
@click,visibility 等於该 Tab 的 Value (all / active / completed )
并且写有当前Tab样式的 active 要维持在 visibility 对应的 Tab
<template v-for="(item, index) in visibilityList">
<li class="nav-item" :key="index">
<a class="nav-link" href="#"
:class="{'active' : visibility == item.value }"
@click="visibility=item.value">
{{item.name}}
</a>
</li>
</template>
清单项目抓取自 filteredTodos 的结果(筛选出当前 Tab 的项目)
<template v-for="(item) in filteredTodos">
<li class="list-group-item">
(略)
</li>
</template>
计算的方法
根据当前的 visibility 回传对应状态的项目
computed: {
filteredTodos() {
let nowTab = this.visibility
switch (nowTab) {
case "all":
return this.todos.filter((item) => true)
case "active":
return this.todos.filter((item) => !item.completed)
case "completed":
return this.todos.filter((item) => item.completed)
}
},
}
<div>{{`还有 ${activeTodosLength} 笔任务未完成`}}</div>
computed: {
activeTodosLength() {
return this.todos.filter((item) =>
!item.completed).length
}
}
}
个人 Blog: https://eudora.cc/
<<: 资安这条路 29 - [渗透测试] 渗透测试流程、资讯安全概论
Uptime - 掌握系统的生命徵象 系列文章 (1/4) - 我们要观测的生命徵象是什麽? (2/...
上次我们已经学会要怎麽从资料库依照各个表取出我们想要的栏位,也可以透过条件筛选的方式过滤我们想要的资...
本文同步更新於blog 情境:目前提供旅游行程的方式 <?php namespace Ap...
在组织经营过程,除了组织能将本身资源/资产运用得当,持续产出商品/提供服务以创造价值(营收),在经营...
昨天讲到可以在XML写入固定的domain, 就是固定的搜寻条件 但是肯定有需求是使用者在A栏位选择...