2022-05-16 Error in mounted hook: "Error: Initialize failed: invalid dom."

前言,项目中要用到echarts,需要获取到dom进行初始化,在获取dom这一步卡住了。

注:本项目大体框架用的是uniapp+vue,一个小程序项目。

vue版本:2.9.6 @vue/cli 4.5.12 npm版本:6.10.3 node版本:v12.10.0

举例:

<template>
    <div ref="box"></div>
</template>

<script>
    export default {
        mounted() {
            console.log(this.$refs.box); // undefined
        }
    }
</script>

<style scoped>

</style>

有网友建议放在this.$nextTick(() => {})里面打印

<script>
    export default {
        mounted() {
            this.$nextTick(() => {
                console.log(this.$refs.box); // undefined
            });
        }
    }
</script>

或者用定时器去延时打印

<script>
    export default {
        mounted() {
            setTimeout(()=>{
                console.log(this.$refs.box); // undefined
            },5000)
        }
    }
</script>

均为undefined

而且,我在非uniapp项目(vue搭建)中运行了该代码,是能够获取到的。

解决方案:使用uniapp的api来获取dom元素。

具体可看这里:https://www.gxlsystem.com/qianduan-4051.html

 

2022-10-27 在小程序中uniapp的ref只能用来获取子组件,且该子组件必须被引用。

posted @ 2022-05-16 18:11  叶乘风  阅读(2692)  评论(0编辑  收藏  举报