vue3 中document.getElementById(‘container‘).scrollWidth = 0 的简单解决方法nextTick

// 定义数据源
const data = {
  // 点集
  nodes: [
    {
      id: 'node1',
      x: 100,
      y: 200,
    },
    {
      id: 'node2',
      x: 300,
      y: 200,
    },
  ],
  // 边集
  edges: [
    // 表示一条从 node1 节点连接到 node2 节点的边
    {
      source: 'node1',
      target: 'node2',
    },
  ],
};


function initG6(){
    const container = document.getElementById('container');
    const width = container.scrollWith || 500;
    const height = container.scrollHeight || 500;
    // 创建 G6 图实例
    const graph = new G6.Graph({
      container: 'mountNode', // 指定图画布的容器 id
      // 画布宽高
      width,
      height,
    });
    // 读取数据
    graph.data(data);
    // 渲染图
    graph.render();
}

onMounted(()=>{
   initG6();
});
<div id="mountNode" />

这样的话,conatiner.scrollWith 代码返回的是0

​
conatiner.scrollWith ==> 0

原因是DOM元素还没有被完全渲染出来。Vue的生命周期钩子可以帮助你确保在正确的时间点获取元素的宽度。

import {
    ref,
    computed,
    unref,
    onMounted,
    nextTick,
  } from 'vue';
onMounted(()=>{
   nextTick(() => {
        initG6();
      });
});

外面只要包裹一个nextTick就可以。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值