♥ $nextTick() in vue

♥ $nextTick() in vue

① Grammar


this.$nextTick(回调函数)


② Function

Executes its specified callback after the end of the next DOM update

When to use----(such as the rendering of Echarts map)
when the data is changed and some operations are to be performed based on the updated new DOM, it must be executed in the callback function specified by nextTick

③ Case:

Click the button, use the text box to modify the title data in the page, and the text box can automatically get the focus, and the text box loses focus to save the modified title, and the text box is hidden

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="root">
        <h1>{
    
    {
    
    title}}</h1>
        <input type="text" v-model="title" v-show="isEdit" ref="inputTitle" @blur="handlerBlur">
        <button v-show="!isEdit" @click="handlerEdit">点击修改标题</button>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script>
const vm = new Vue({
    
    
    el: '#root',
    data: {
    
    
        title: 'hello world',
        // 是否处于编辑状态
        isEdit: false
    },
    methods: {
    
    
        // 对标题进行编辑
        handlerEdit() {
    
    
            // 修改状态为编辑状态
            this.isEdit = !this.isEdit
            // 直接让输入框获取焦点
            // 此时函数中的代码还未完全执行完成,vue不会进行模板的重新解析
            // 所以更新后的还未放入页面,此时获取焦点无效
            // this.$refs.inputTitle.focus()

            // 使用nextTick()在页面解析完成后让文本框获取焦点
            // 基于更新后的新输入框进行操作,使其获取焦点
            this.$nextTick(() => {
    
    
                this.$refs.inputTitle.focus();
            })
        },
        // 处理文本框失去焦点
        handlerBlur() {
    
    
            // 修改状态为不处于编辑状态
            this.isEdit = !this.isEdit
        }
    },
})
</script>

</html>

Guess you like

Origin blog.csdn.net/weixin_43615570/article/details/132208296