Todo-list编辑功能
- 新增编辑按钮和input输入框并添加相应样式
- 点击编辑按钮,文本内容隐藏,input显示,其中的值为文本相应的值
- 修改其中的值,在input输入框失去焦点时更新修改内容
App组件
methods: {
// 修改一个任务项
updateTodo(id,tittle){
this.todoArr.forEach((todo) => {
if (todo.id === id) {
todo.tittle = tittle
}
})
},
},
mounted() {
this.$bus.$on('updateItem',this.updateTodo)
},
beforeDestroy() {
this.$bus.$off([updateItem'])
}
<script>
.btn-edit {
color: #ffffff;
background-color: #66B1FF;
border: 1px solid #409EFF;
}
.btn-edit:hover {
color: #ffffff;
background-color: #409EFF;
}
</script>
Item组件
<span v-show="!todo.isEdit">{{ todo.tittle }}</span>
<input type="text"
:value="todo.tittle"
v-show="todo.isEdit"
ref="inputTitle"
@blur="handleBlur(todo,$event)">
<button class="btn btn-edit" @click="editTodoItem(todo)" v-show="!todo.isEdit">编辑</button>
// 编辑任务项
editTodoItem(todo) {
if (todo.hasOwnProperty('isEdit')){
todo.isEdit=true
}else {
this.$set(todo, 'isEdit', true)
}
},
// 失去焦点回调 执行修改逻辑
handleBlur(todo,e){
todo.isEdit=false
if (!e.target.value.trim()) return alert('输入不能为空')
this.$bus.$emit('updateItem',todo.id,e.target.value)
}
$nestTick
- 语法:
this.$nextTick(回调函数)
- 作用:在下一次DOM更新结束后执行其指定的回调
- 使用:在数据改变后,需要基于更新后的新DOM进行某些操作时,在nextTick指定的回调函数中执行
Todo-list自动获取焦点
// 编辑任务项
editTodoItem(todo) {
if (todo.hasOwnProperty('isEdit')){
todo.isEdit=true
}else {
this.$set(todo, 'isEdit', true)
}
this.$nextTick(function (){
this.$refs.inputTitle.focus()
})
},