$nextTick 方法的作用,就是当页面上元素被重新渲染之后,才会指定回调函数中的代码
例子如下
点击按钮后,按钮变成输入框,并且聚焦于输入框
<!-- -->
<template>
<div>
<!-- 输入的文本框 -->
<el-input
class="input-new-tag"
v-if="inputVisible"
v-model="inputValue"
ref="saveTagInput"
size="small"
@keyup.enter.native="handleInputConfirm"
@blur="handleInputConfirm"
>
</el-input>
<!-- 添加按钮 -->
<el-button v-else class="button-new-tag" size="small" @click="showInput"
>+ New Tag</el-button
>
</div>
</template>
<script>
export default {
data () {
return {
inputVisible: false,
inputValue: ''
}
},
components: {},
computed: {},
mounted () {},
methods: {
// 点击按钮,展示文本输入框
showInput () {
this.inputVisible = true
// 点击按钮,展示文本输入框,并且让文本框自动获得焦点
// $nextTick 方法的作用,就是当页面上元素被重新渲染之后,才会指定回调函数中的代码
this.$nextTick(_ => {
this.$refs.saveTagInput.$refs.input.focus()
})
},
handleInputConfirm () {
if (!this.inputValue) {
this.inputVisible = false
}
}
}
}
</script>
<style lang="less" scoped>
.input-new-tag {
width: 120px;
}
</style>