IMWeb训练营作业
VueJS 学习 —— Todo
Demo (点击预览)
ps: 在线demo为github page,国内网络或出现不能访问情况
时间问题,作业仅支持移动端
介绍(代码地址)
作业使用 vue-cli
搭建开发环境,修改了部分 webpack
配置,采用模块化开发形式,部分内容加入了动画效果,支持双击 todo
进行编辑,支持 hash
监听,没有设计师,视觉呈现请dalao多见谅
目录结构
核心代码
双击编辑
采用监听点击同个元素的间隔时间是否小于 500毫秒
来判断是否触发该 todo
的编辑状态,若符合双击操作,则使用 App.touchInfo
对编辑 todo
及 隐藏 input
输入的 text
进行缓存
<!-- src/App.vue -->
<todo-item
:todo="todo"
:key="todo.id"
:editTodo="editTodo"
:touchInfo="touchInfo"
:deleteTodo="deleteTodo"
:handleTouchEnd="handleTodoTouchEnd"
v-for="(todo, index) in filteredTodoList"
/>
// src/App.js
import TodoItem from 'components/TodoItem'
// 双击间隔最大时间
const DOUBLE_TOUCH_TIME = 500
export default {
name: 'app',
components: {
TodoItem
...
},
...
data () {
return {
...
// 点击数据缓存对象
touchInfo: {
todo: null,
text: null,
timeStamp: 0
}
}
},
methods: {
...
// 监听点击事件
handleTodoTouchEnd (e, todo) {
const { timeStamp } = this.touchInfo
const now = new Date().getTime()
if (now - timeStamp <= DOUBLE_TOUCH_TIME) {
this.touchInfo.todo = todo
this.touchInfo.text = todo.text
}
this.touchInfo.timeStamp = now
}
},
...
}
<!-- src/components/TodoItem.vue -->
<template>
<li
class="todo-item"
:class="{
isEdit: this.isEdit,
isChecked: todo.isChecked
}"
>
<!-- ... -->
<label @touchend="handleTouchEnd($event, todo)">{{todo.text}}</label>
<input
type="text"
ref="_input"
v-model="touchInfo.text"
@blur="changeTodoText"
@submit.prevent="changeTodoText"
@keyup.enter.prevent="changeTodoText"
/>
<!-- ... -->
</li>
</template>
<script>
export default {
name: 'todo-item',
props: ['todo', 'touchInfo', 'editTodo', 'deleteTodo', 'handleTouchEnd'],
methods: {
// 修改todo内容
changeTodoText () {
this.$refs._input.blur()
this.editTodo()
}
},
computed: {
// 是否处于编辑状态
isEdit () {
const { todo, touchInfo } = this
return todo === touchInfo.todo
}
},
// 更新时监听编辑状态并focus input
updated () {
if (this.isEdit) {
this.$refs._input.focus()
}
}
}
</script>
hash 监听
以参数形式将监听的 hash
传递给子组件 App
// src/main.js
// 实例化
const app = new Vue({
el: '#app',
template: '<App :status="status"/>',
components: { App },
data () {
return {
status: 'all'
}
}
})
// 监听hash变化
window.onhashchange = () => {
const status = window.location.hash.split('#')[1]
app.status = status
}
End
作业完成的比较仓促,可能会存在较多的不足,如有做的不好的地方,请各位dalao多多指点