浅谈vue3.x $nextTick和 $refs用法

vue3.x $nextTick和 $refs用法
在会使用vue2.x语法后,正在学习vue3语法,记录一下 $nextTick和 $refs用法,下面是一个demo,实际演示如何使用
话不多说直接上代码(这里ui用的是elementUi)

<template>
    <el-button type="" @click="clickShow">显示弹窗</el-button>

    <el-dialog  v-model="flag" width="500px" :show-close="false">
        <div style="width: 100%; height: 300px;">
            <div ref="componentRef">
                获取Dom结构
            </div>
        </div>
    </el-dialog>
</template>

<script lang="ts">
    import {
    
    ref, nextTick } from "vue";

    export default {
    
    
        name: "aa",
        setup() {
    
    
            const flag = ref(false);
            const componentRef = ref(null)
            //或者 
            //泛型默认值语法<T = any>
			   // type Ref<T = any> = {
    
    
			       // value : T
			   // }
			   // const componentRef: Ref<div | null> = ref(null);

            const clickShow = ()=>{
    
    
                flag.value = true;
                //此处显示null,是因为弹框刚显示出来,componentRef的div-dom结构还未加载完
                console.log(componentRef.value);
                handleNextTick();
            }
            //利用nextTick()实现vue2.x中的$nextTick
            const handleNextTick = async ()=>{
    
    
                await nextTick();
                //利用定义的componentRef获取dom结构
                console.log(componentRef.value);
            }

            return {
    
    
                flag,
                componentRef,
                clickShow
            };
        },

    };
</script>

本人也是正在学习vue3语法,如果有更好的写法,还请各位大神不吝赐教哦~

猜你喜欢

转载自blog.csdn.net/qq_37656005/article/details/119805722