Vue's this.$refs.xxx error undefined solution

Table of contents

1. Background

Two, the solution

1. Call after the DOM is loaded

2. The subcomponent is not called when it is loaded for the first time


1. Background

Register child components with ref, the parent component can this.$refs.xx.fncall the function in the child component,

When the page is initialized, this.$refs.xxxit prompts undefined when it is called. At first I thought the method failed, but later I found out

Because the refs themselves are created as a result of rendering, you can't access them during the initial render - they don't exist yet! $refs is also not reactive, so you should not attempt to use it for databinding in templates. "

That is to say, you can only call ref after the page is loaded this.$refs. If you use v-if and v-for to render the page, you can't get it before the page is rendered at the beginning this.$refs, so you have to wait until the page is rendered. You can take it later.

Two, the solution

1. Call after the DOM is loaded

Understanding of Life Cycle: Detailed Explanation of created and mounted in Vue_vue mounted_Mubai Lee's Blog-CSDN Blog

demoMethod() {
  this.$nextTick(() => {
    ...
  })
},

2. The subcomponent is not called when it is loaded for the first time

Define the first call state

data(){
    return {
        updalod:{
            isFirst:false,
        }
    }
}

Applicable to specific scenarios, and then the first rendering is not executed. It should be noted that the defined variables need to be under the sub-component, otherwise they will not be available

Please like it if it is useful, and develop a good habit!

Please leave a message for encouragement, communication, and questions!

Guess you like

Origin blog.csdn.net/libusi001/article/details/131523807