nextTick:
MyItem.vue
加一个编辑按钮,input框:@blur失去焦点时触发事件handleBlur,ref获取真实dom:
<inputtype="text"v-show="todo.isEdit":value="todo.title"@blur="handleBlur(todo,$event)"ref="inputTitle"><button class="btn btn-edit" @click="handleEdit(todo)" v-show="!todo.isEdit">编辑</button>
methods加俩方法:
//编辑handleEdit(todo){if (todo.hasOwnProperty.call('isEdit')){todo.isEdit = true}else {console.log('a@@')this.$set(todo,'isEdit',true)}// setTimeout(()=>{// this.$refs.inputTitle.focus()// },20)this.$nextTick(function (){this.$refs.inputTitle.focus()})},//失去焦点回调(真正执行修改逻辑)handleBlur(todo,e){todo.isEdit=falseif (!e.target.value.trim())return alert('输入不能为空')this.$bus.$emit('updateTodo',todo.id,e.target.value)}
App.vue:
methods:中加一个方法
//更新一个todoupdateTodo(id,title){this.todos.forEach((todo)=>{if (todo.id===id)todo.title=title})},
mounted钩子中添加
this.$bus.$on('updateTodo',this.updateTodo)
beforeDestroy钩子中添加
this.$bus.$off('updateTodo')
style中加编辑按钮样式:
.btn-edit {color: #fff;background-color: skyblue;border: 1px solid #0f7daa;margin-right: 3px;
}