vue3 uses ref to get the dom result as 'null'

In vue2, when we use ref to get the dom element, it looks like this:

// 父组件
<template>
  <div>
    <button @click=handleClick>我装载了一个子组件!</button>
    <son ref="dataList"></son>
  </div>
</template>

<script>
import son from './data.vue'
export default {
  components: {
    son
  },
  methods:{
    handleClick(){
      console.log(this.$refs.dataList)  //像这样!
    }
  }
}
</script>

In vue3, when we use ref to get the dom element, it looks like this:

// 父组件
<template>
  <button @click=handleClick>我装载了一个子组件!</button>
  <son ref="dataList"></son>
</template>

<script>
import {ref} from 'vue'
import son from './data.vue'
export default {
  setup(){
    const dataList=ref(null)
    const handleClick=()=>{
      console.log(dataList.value)  //像这样!
    }
    return{
      dataList //这里要抛出响应式数据才可使用。
    } 
  }
}
</script>

Let’s talk about the reason why the dom is empty in vue3:

  1. The field encapsulated by ref should be thrown in the return of setup, otherwise the value of ref is only defined and cannot be used reactively. In fact, all values ​​defined by ref or reactive should be thrown in the return.

  1. Print directly in setup(). This is a life cycle issue. Setup is essentially equivalent to create in vue2. During the creation phase, the dom element has not been completely created. At this time, it is naturally null to obtain the dom. In the above example, I triggered it when clicking the button. At this time, it has already passed the creation stage. If you want to do it earlier, you can manually define onMented to print, as follows:

import {ref,onMented} from 'vue'
export default {
  setup(){
    const dataList=ref(null)
    onMented(()=>{
      console.log(dataList.value)  //像这样!
    })
    return{
      dataList 
    } 
  }
}
  1. If when you use it, ref.value cannot get the value in the subcomponent, or an error is reported that the ref.value object is empty, it is because the subcomponent needs to expose methods that can be called by the negative component. Add this to the subcomponent. Just go to defineExpose.

defineExpose({
  onOpen  //这是你要调用的方法名
});

Guess you like

Origin blog.csdn.net/m0_56683897/article/details/129709604