Summary of Vue knowledge points (20)-basic concepts and practical applications of nextTick (super detailed)

Today's protagonist is nextTick , which is an API officially provided by Vue.
Before introducing it, we must first understand one thing.

Maybe you haven't noticed that Vue updates the DOM asynchronously. As long as it listens to data changes, Vue will open a queue and buffer all data changes that occur in the same event loop. If the same watcher is triggered multiple times, it will only be pushed to the queue once.

This is a brief introduction to Vue's asynchronous update of the DOM queue in the official Vue documentation .

In fact, we know that one thing is enough, Vue is executed asynchronously when updating the DOM . Everyone should know what asynchronous is. If you don't know, you can check my previous blog.

What is the downside of asynchronous execution is that when we need to use the DOM, it is still being loaded, and it is not actually updated, but the previous or subsequent operations are updated.
Anyway, it will cause us to be unable to obtain the DOM update result normally.

Let's take a look at a simple example first.

<div id="app">
    {
   
   {message}}
</div>
   <script>
        const vm = new Vue({
    
    
            el:'#app',
            data:{
    
    
                message:'Ray'
            }
        });
        vm.message = 'CreatorRay';  
        console.log(vm.$el.textContent);
    </script>

We wrote a simple vue instance vm, and then changed its internal data value by manipulating the vm object, changing the message from Ray to CreatorRay .
Then get the updated content through vm.$el.textContent .

Let's look at the result: The content of
Insert picture description here
vm.$el.textContent is Ray.

What this shows, we did not get the updated data . This is the result of Vue rendering the DOM asynchronously .

This is very uncomfortable and may hinder us from actual logic development.

Therefore, the role of the nextTick API is here.
Now we add the following code:

Vue.nextTick(()=> {
    
    
    console.log(vm.$el.textContent);
});

Look again at the console after the page is rendered.
Insert picture description here
In this way, we can get the actual data update result.

This is just one of the simplest use of nextTick

Let's take a look at the actual application of nextTick in development with a real development requirement .

demand:

We now have a pop-up component that has been developed, and the triggering conditions of the pop-up are provided by the backend. In other words, when the pop-up window is triggered is completely determined by the data provided by the backend.

<div id="app">
    <App></App>
</div>
<script>
    const Pop = {
    
    
        data () {
    
    
            return {
    
    
                isShow:false
            }
        },
        props:{
    
    
            name:{
    
    
                type:String,
                default:''
            }
        },
        template:`
            <div v-if='isShow'>
                {
     
     {name}}
            </div>
        `,
        methods: {
    
    
            show(){
    
    
                 if(this.name == '触发'){
    
    
                   this.isShow = true; // 弹窗组件展示
                }
                console.log(this.name);
            }
        }
    }
    const App = {
    
    
        data () {
    
    
            return {
    
    
                name:'不触发'
            }
        },
        created () {
    
    
            // 模拟异步请求
            setTimeout(()=>{
    
    
                // 数据更新
                this.name = '触发';
                this.$refs.pop.show();
                /*this.$nextTick(()=> {
                    this.$refs.pop.show();
                })*/
            },1000)
        },
        components: {
    
    
            Pop
        },
        template:`<Pop ref='pop' :name='name' ></Pop>`
    }
    new Vue({
    
    
        el:'#app',
        data:{
    
    

        },
        components:{
    
    
            App
        }
    });
</script>

I just simply mean the code.
A partial component Pop serves as our pop-up component . A partial component App . In the App component, Pop is used, and the ref attribute is written to the Pop component , and through the parent-child component communication , a set of values ​​named name is passed to the child component . This name is the condition that triggers the pop-up component .

Then take a look at the created lifecycle hook of the App component . Let's simulate the request to the back-end interface. To save time, I will simulate the asynchronous request through setTimeout .

Assuming that the data name we get is trigger , we pass this.name='trigger' . Update the existing data. The name is trigger , which is the condition for triggering the pop-up component . Now we have to trigger it show Pop method of sub-assemblies . It happens that we have attached the ref attribute to the Pop component , and we can directly get the Pop component object and call its method, which is very good. Let's see if we can succeed through the conventional method. Call the method of the child component
directly through this.$refs.pop.show() .
Take a look at the result:
Insert picture description here
The show method of the subcomponent is indeed successfully called
, but the name value output in the show method is not triggered , and the content on the page is not rendered . This shows that the operation of modifying the name value in setTimeout did not update the subcomponents in time .

Ok, let's try nextTick next .
First comments about the this $ refs.pop.show (). ;
Add the following to the code:

        this.$nextTick(()=> {
            this.$refs.pop.show();
        })

Now look at the result:
Insert picture description here
The name value output in the show method is triggered, and the "pop-up content" on the page is also rendered.

okkkkkk, great.

This is the application of nextTick in our actual business development, and it is still very useful.

Although Vue recommends that we use a "data-driven" way of thinking and avoid direct contact with the DOM, sometimes we have to do this. nextTick is our good helper.


There is a WeChat mini program course design, complete design needs, contact personal QQ: 505417246

Pay attention to the following WeChat public account, you can receive WeChat applet, Vue, TypeScript, front-end, uni-app, full stack, Nodejs, Python and other practical learning materials. The
latest and most complete front-end knowledge summary and project source code will be released to the WeChat public as soon as possible No., please pay attention, thank you!

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46171043/article/details/112626412