如何仅在 Vue 完全加载和初始化后运行 VueJS 代码? [英] How to run VueJS code only after Vue is fully loaded and initialized?

查看:35
本文介绍了如何仅在 Vue 完全加载和初始化后运行 VueJS 代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Vue 组件,该组件将通过 CMS 系统放置在多个网站上.我遇到的问题是,即使我的 js 脚本加载顺序正确,有时我也会收到此错误:

I am working on a Vue component that will be placed on multiple websites via a CMS system. The issue I encounter is that even if my js scripts loading order is correct, sometime I get this error:

Uncaught ReferenceError: Vue is not defined
    at HTMLDocument.<anonymous>

Vue 通过 cdn 加载,并且位于组件代码之上.

Vue is loaded via cdn and it's above the component's code.

所有的Vue代码都是这样运行的:

All the Vue code is run like this:

document.addEventListener("DOMContentLoaded", () => {
  // here is the Vue code
});

我什至在 DOMContentLoaded 事件中添加了一个 setTimeout() ,但仍然没有成功.window.onload = function() 在所有情况下都不起作用.我仍然不时遇到那个错误.脚本加载在正文中.

I even added a setTimeout() inside the DOMContentLoaded event and still did not do the trick. window.onload = function() did not work either in all cases. I still got that error from time to time. The scripts are loaded in the body.

你知道它可以是另一种方法吗?我想确保在触发 Vue 代码的那一刻,Vue 已加载并准备好在页面上进行初始化.谢谢!

Do you have any idea what it can be another approach? I want to be sure that in the moment the Vue code is fired, Vue is loaded and ready to be initialized on the page. Thank you!

推荐答案

使用 加载事件等待所有资源加载完成:

Use the load event to wait until all resources have finished loading:

<script>
  window.addEventListener("load", function(event) {
    // here is the Vue code
  });
</script>

进一步说明

DOMContentLoaded 是在解析 HTML 和渲染并构建 DOM.它通常在应用程序的生命周期.另一方面, load 仅在所有资源(图像、样式表等)都从网络并可供浏览器使用.

DOMContentLoaded is an event fired when the HTML is parsed and rendered and DOM is constructed. It is usually fired pretty fast in the lifetime of the app. On the other hand, load is only fired when all the resources (images, stylesheets etc.) are retrieved from the network and available to the browser.

您还可以使用特定脚本的加载事件.

这篇关于如何仅在 Vue 完全加载和初始化后运行 VueJS 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆