美文网首页
Vue3.0中使用$refs的使用注意事项

Vue3.0中使用$refs的使用注意事项

作者: 安之烟波客 | 来源:发表于2022-12-28 08:52 被阅读0次

第一次使用vue3.0做echarts图表展示的时候,需要获取到dom信息,刚开始使用document.getElementById来获取dom,但是获取不到,在网上百度了一下,建议使用$refs,所以就试着用这种方法去做,老是获取不到信息,在onMounted里边去打印的时候结果为null,最后无意中在return 中增加了ref的变量值,这下直接打印出来了。以下为选项模式下代码。

<template>
  <div class="container">
    <div ref="chartref" style="height:300px">
    </div>
  <div>
</template>
<script lang="ts">
  import { ref, defineComponent, onMounted } from 'vue';
export default defineComponent({
  setup(){
    //  该变量名称要与模板中的ref值保持一致,不然会出现null
     const chartRef = ref<HTMLElement | any>();
     onMounted(()=>{
        console.log('chartRef',chartRef)
      })
     return {
        chartRef // 这个是重点,一定要return
    }
  }
})
</script>

相关文章

网友评论

      本文标题:Vue3.0中使用$refs的使用注意事项

      本文链接:https://www.haomeiwen.com/subject/lrnaqdtx.html