gpt4 book ai didi

javascript - VueJS - v-if 和 v-show 无法正常工作

转载 作者:行者123 更新时间:2023-11-28 04:21:06 24 4
gpt4 key购买 nike

我在 Vue DIV 中有这个结构:

            <div class="row">
<div class="well chart-container">
<div id="chart" v-if="chartShown"></div>
<h1 v-if="textShown">{{staticPropertyValue}}</h1>
</div>
</div>

在我的应用程序中,我希望能够显示图表 div 或 h1 标签。这是我的 JavaScript 的一部分:

app.textShown = false;
app.chartShown = true;

if (data.length == 0) {
MG.data_graphic({
title: "Missing Data",
description: "",
error: 'No data',
chart_type: 'missing-data',
missing_text: 'There is no data',
target: '#chart',
full_width: true,
height: 600
});

return;
};

if (data.length == 1) {
app.staticPropertyValue = data[0].value;
app.chartShown = false;
app.textShown = true;
return;
}

console.log('DRAWING GRAPH');
console.log(document.getElementById('chart'));
MG.data_graphic({
title: "Fetched data",
description: "",
data: data,
full_width: true,
height: 600,
target: '#chart',
x_accessor: 'time',
y_accessor: 'value'
});

因此,根据 data.length 属性,显示图表或显示 h1 标签。当我第一次调用上面的代码并显示 h1 标记(因为 data.length == 1),然后下次我用 date.length > 1 调用它(图表应该出现)时,问题就出现了。我收到错误:

The specified target element "#chart" could not be found in the page. The chart will not be rendered.

它来 self 用来绘制图表的库——metricsgraphics.js。所以我控制台记录了

的结果
document.getElementById('chart')

它是。所以这意味着虽然我将 ChartShown 切换为 true,但它做得不够快。我该如何解决这个问题?

我还尝试使用 v-show 而不是 v-if - 效果不佳 - 我对某些元素的宽度为 NaN 遇到了一些错误。

最佳答案

您应该在组件的 mounted() 回调中运行这段代码。

对我来说,看起来你是在脚本完成加载时运行它,这不一定是在 DOM 完全构建时,也绝对不是在 Vue 完成渲染其组件时。

在使用外部库时使用 v-if 无论如何都不是一个好主意,最好在 mounted() 回调中初始化 View 并然后观察你的 chartShown 变量,如下所示:

{
...,
watch: {
chartShown(nv) {
if (nv) {
// setup chart
} else {
// remove chart
}
}
},
...
}

关于javascript - VueJS - v-if 和 v-show 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45431413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com