external script doesn't always loads when we navigate between components nuxt 3

huangapple go评论68阅读模式
英文:

external script doesn't always loads when we navigate between components nuxt 3

问题

外部脚本在切换组件时并不总是加载。我在Nuxt 3中创建了一个名为dashboard/index.vue的组件,并添加了以下代码:

```javascript
useHead({
    script: [
        {
            src: 'https://code.highcharts.com/highcharts.js',
            type: 'text/javascript',
            async: true,
            body: true
        },
    ],
});

这是我在onMounted中使用的函数:

const initializeCharts = () => {
    window.Highcharts.chart('highchart-1', {
        // ...(此处为一段配置代码)
    });
};

当我们从一个页面导航到仪表板页面时,脚本不会加载。但当我们重新加载仪表板页面时,它就能正常工作了。我尝试过添加onMounted、onBeforeUpdate以及许多其他生命周期钩子,但最终我看到了同样的错误。我正在使用Nuxt 3。以下是StackBlitz的代码:

https://stackblitz.com/edit/github-kqvufh


<details>
<summary>英文:</summary>

external script doesn&#39;t always loads when we navigate between components nuxt 3 , i have created component 
dashboard/index.vue
added this code

useHead({
script: [
{
src: 'https://code.highcharts.com/highcharts.js',
type: 'text/javascript',
async: true,
body: true
},
],
});


this it the function i am using in onMounted

    const initializeCharts = () =&gt; {
        window.Highcharts.chart(&#39;highchart-1&#39;, {
            chart: {
                type: &#39;spline&#39;,
                height: 310
            },
            title: {
                text: &#39;Monthly Average Temperature&#39;
            },
            xAxis: {
                categories: [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;, &#39;Jun&#39;,
                    &#39;Jul&#39;, &#39;Aug&#39;, &#39;Sep&#39;, &#39;Oct&#39;, &#39;Nov&#39;, &#39;Dec&#39;],
                accessibility: {
                    description: &#39;Months of the year&#39;
                }
            },
            yAxis: {
                title: {
                    text: &#39;Temperature&#39;
                },
                labels: {
                    format: &#39;{value}&#176;&#39;
                }
            },
            tooltip: {
                crosshairs: true,
                shared: true
            },
            plotOptions: {
                spline: {
                    marker: {
                        radius: 4,
                        lineColor: &#39;#666666&#39;,
                        lineWidth: 1
                    }
                }
            },
            series: [{
                name: &#39;Tokyo&#39;,
                marker: {
                    symbol: &#39;square&#39;
                },
                data: [5.2, 5.7, 8.7, 13.9, 18.2, 21.4, 25.0, {
                    y: 26.4,
                    marker: {
                        symbol: &#39;url(https://www.highcharts.com/samples/graphics/sun.png)&#39;
                    },
                    accessibility: {
                        description: &#39;Sunny symbol, this is the warmest point in the chart.&#39;
                    }
                }, 22.8, 17.5, 12.1, 7.6]
    
            }, {
                name: &#39;Bergen&#39;,
                marker: {
                    symbol: &#39;diamond&#39;
                },
                data: [{
                    y: 1.5,
                    marker: {
                        symbol: &#39;url(https://www.highcharts.com/samples/graphics/snow.png)&#39;
                    },
                    accessibility: {
                        description: &#39;Snowy symbol, this is the coldest point in the chart.&#39;
                    }
                }, 1.6, 3.3, 5.9, 10.5, 13.5, 14.5, 14.4, 11.5, 8.7, 4.7, 2.6]
            }]
        });

when we navigate from one page to dashboard page it doesn&#39;t loads , when we reload the dashboard page then it works fine as expected 

i have tried adding onMounted, onBeforeUpdate and many other lifecycle hooks but at the end i see the same error,
i am using nuxt3
here is the stackblitz code 

[https://stackblitz.com/edit/github-kqvufh][1]


  [1]: https://stackblitz.com/edit/github-kqvufh

</details>


# 答案1
**得分**: 1

错误发生是因为您在页面的`onMounted`钩子中使用了`initializeCharts`,这可能会在从CDN获取脚本之前发生。这导致`initializeCharts`无法找到脚本提供的`window.Highcharts`。

解决方法是确保仅在获取脚本后才运行该函数。可以通过在`useHead`中的`onload`钩子内调用`initializeCharts`来实现,如下所示:

```vue
useHead({
  script: [
    {
      src: 'https://code.highcharts.com/highcharts.js',
      onload: () => { initializeCharts() },
    }
  ]
});

onMounted(() => {
  // 这不再需要,可以删除
  // initializeCharts(); 
});

检查这个Stackblitz链接,您将会发现在两种情况下都存在脚本标签(直接打开仪表板页面或从索引页面使用链接导航到它)。

英文:

The error happens because your using the initializeCharts in the page onMounted hook which may happen before fetching the script from the CDN. This leads to initializeCharts not finding the window.Highcharts provided by the script.

The solution is ensure running the function only after the script is fetched. This can be done by calling initializeCharts inside the onload hook in useHead like the following

useHead({
  script: [
    {
    src: &#39;https://code.highcharts.com/highcharts.js&#39;,
    onload: () =&gt; { initializeCharts() },
    }
  ]
});

onMounted(() =&gt; {
  // This is no longer needed and can be removed
  // initializeCharts(); 
});

Check this Stackblitz Link with the applied changes, you'll find the script tag present in both cases (directly opening the dashboard page or naviagting to it from the index page using the link)

huangapple
  • 本文由 发表于 2023年7月18日 09:21:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定