$nextTick
有时候需要在解析模板后再执行相应的回调,但是Vue会在执行完全部的区域代码再解析模板,这时候就需要用到$nextTick了
示例:
<template>
<li>
<label>
<!-- 如下代码也能实现功能,但是不太推荐,因为有点违反原则,因为修改了props -->
<!-- <input type="checkbox" v-model="todo.done"/> -->
<input
type="checkbox"
:checked="todo.done"
@change="handleCheck(todo.id)"
/>
<span v-show="!todo.isEdit">{{ todo.title }}</span>
<input
v-show="todo.isEdit"
type="text"
:value="todo.title"
@blur="handleBlur(todo, $event)"
ref="inputPart"
/>
</label>
<button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
<button
v-show="!todo.isEdit"
class="btn btn-edit"
@click="handleEdit(todo)"
>
编辑
</button>
</li>
</template>
<script>
export default {
name: "MyItem",
props: ["todo"],
methods: {
handleCheck(id) {
//this.checkTodo(id);
this.$bus.$emit("checkTodo", id);
},
handleDelete(id) {
//this.deleteTodo(id);
this.$bus.$emit("deleteTodo", id);
},
handleEdit(todo) {
if (Object.prototype.hasOwnProperty.call(todo, "isEdit")) {
todo.isEdit = true;
} else {
this.$set(todo, "isEdit", true);
}
this.$nextTick(function () {
this.$refs.inputPart.focus();
});
},
//失去焦点回调
handleBlur(todo, e) {
todo.isEdit = false;
if (!e.target.value.trim()) return alert("输入不能为空");
this.$bus.$emit("updateTodo", todo.id, e.target.value);
},
},
};
</script>
事实上也可以设置没有时间的定时器,即回调函数直接执行,但是最好还是用$nextTick