Vue3 ref understanding and usage

1. ref 

Like reactive ,          ref is also a method for implementing responsive data

2. Essence

        The bottom layer of ref is actually reactive, so when running, the system will automatically convert it to reactive according to the incoming ref

3. use

         ① The value of ref used in vue does not need to be obtained through value

         ② The value of ref used in js must be obtained through value

         

<template>
    <div>
        <button @click="click"></button>
        // 直接引用变量获取值
        <p>{
   
   {num}}</p>
    </div>
</template>
<script lang="ts">
import { defineComponent,ref } from 'vue'

export default defineComponent({
    setup() {
        // 声明双向数据ref
        const num=ref()
        // js 通过.value 获取值
        num.value=123;
        const click = ()=>{
            num.value+=1;
        }
        return {
            num,
            click
            }
    },
})
</script>

        ③Get elements by ref

   In vue2, we can add ref='xxx' to the element, and then get the element through refs.xxx in the code. In vue3, we can also get the element through ref. But not in the familiar way like the following, Because there are no such things as $ and refs in vue3.

  

<template>
    <div ref="div">
     这个是div
    </div>
</template>
<script lang="ts">
import { defineComponent,onMounted,ref } from 'vue'

export default defineComponent({
    setup() {
       const div=ref(null) //本质是reactive({value:null})
       // 错误用法
       // this.$refs.div

       //正确用法

       // 需要再onMountd 生命周期内使用
       onMounted(()=>{ 
           // 界面挂载完后 会执行
           console.log(div.value)
       })
       //接受的是null,原因是setup执行时机比mounted早,dom还没形成 注意vue3的生命周期
        console.log(div.value);// 执行早于 onMounted
        return {
            div
            }
    },
})
</script>
... 

输出结果
  null
  <div>这个是div</div>

Guess you like

Origin blog.csdn.net/sinat_37792529/article/details/124375393