如何仅在 Vue 完全加载和初始化后运行 VueJS 代码?

新手上路,请多包涵

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

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

Vue 是通过 cdn 加载的,它位于组件的代码之上。

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

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

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

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

原文由 Bogdan Lungu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

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

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

进一步说明

DOMContentLoaded 是在解析和呈现 HTML 并构造 DOM 时触发的事件。它通常在应用程序的生命周期内很快被触发。另一方面, load 仅在所有资源(图像、样式表等)从网络中检索并可供浏览器使用时才会触发。

您还可以 对特定脚本使用 load 事件

原文由 Roy J 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 vue mounted() 在页面加载时运行任何代码,并使用 updated() 在任何组件操作之后运行,因此一个完美的解决方案是结合 Roy j 和 vue 生命周期挂钩

mounted() {
    window.addEventListener('load', () => {
         // run after everything is in-place
    })
},

// 99% using "mounted()" with the code above is enough,
// but incase its not, you can also hook into "updated()"
//
// keep in mind that any code in here will re-run on each time the DOM change
updated() {
    // run something after dom has changed by vue
}

请注意,您可以省略 window.addEventListener() 它仍然可以工作,但它可能会错过 + 如果您使用的是 jquery outerHeight(true) 最好在窗口事件中使用它以确保您正在获得正确的值。

更新 1:

而不是 window.addEventListener('load') 还有另一种方法使用 document.readyState 所以上面可以是

mounted() {
  document.onreadystatechange = () => {
    if (document.readyState == "complete") {
        // run code here
    }
  }
},

更新 2:

到目前为止我发现的最可靠的方法是在 debounce 上使用 $nextTick ,所以用法变成

import debounce from 'lodash/debounce'

// bad
updated() {
    this.$nextTick(debounce(() => {
        console.log('test') // runs multiple times
    }, 250)) // increase to ur needs
}

// good
updated: debounce(function () {
    this.$nextTick(() => {
        console.log('test') // runs only once
    })
}, 250) // increase to ur needs

当使用 debounce with updated 时它变得棘手,所以一定要继续测试它 b4。

更新 3:

你也可以尝试 MutationObserver

原文由 ctf0 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题