Javascript 如何仅在 Vue 完全加载和初始化后运行 VueJS 代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43652265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run VueJS code only after Vue is fully loaded and initialized?
提问by Bogdan Lungu
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:
我正在开发一个 Vue 组件,该组件将通过 CMS 系统放置在多个网站上。我遇到的问题是,即使我的 js 脚本加载顺序正确,有时我也会收到此错误:
Uncaught ReferenceError: Vue is not defined
at HTMLDocument.<anonymous>
Vue is loaded via cdn and it's above the component's code.
Vue 是通过 cdn 加载的,它位于组件代码之上。
All the Vue code is run like this:
所有的 Vue 代码都是这样运行的:
document.addEventListener("DOMContentLoaded", () => {
// here is the Vue code
});
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.
我什至在 DOMContentLoaded 事件中添加了一个 setTimeout() ,但仍然没有成功。
window.onload = function()在所有情况下都不起作用。我仍然时不时地遇到那个错误。脚本加载在正文中。
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!
你知道它可以是另一种方法吗?我想确保在触发 Vue 代码的那一刻,Vue 已加载并准备好在页面上进行初始化。谢谢!
回答by ctf0
use vue mounted()to run any code on page load, and updated()to run after any component operations, so a perfect solution would be combining both Roy jand vue lifecycle hooks
使用 vuemounted()在页面加载时运行任何代码,并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
}
note that you can omit the window.addEventListener()and it still going to work but it might miss + if you are using something like jquery outerHeight(true)its better to use it inside the window event to make sure you are getting correct values.
请注意,您可以省略它window.addEventListener(),它仍然可以工作,但如果您使用诸如 jquery 之类的东西,它可能会错过 +outerHeight(true)最好在 window 事件中使用它以确保您获得正确的值。
Update 1 :
更新 1:
instead of window.addEventListener('load')there is also another way by using document.readyStateso the above can be
而不是window.addEventListener('load')还有另一种方式使用document.readyState所以上面可以
mounted() {
document.onreadystatechange = () => {
if (document.readyState == "complete") {
// run code here
}
}
},
Update 2 :
更新2:
the most reliable way i've found so far would be using debounceon $nextTick, so usage becomes
到目前为止我发现的最可靠的方法是使用debounceon $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
when using debouncewith updatedit gets tricky, so make sure to test it b4 moving on.
当使用带有更新的去抖动时它会变得棘手,所以一定要继续测试它 b4。
Update 3 :
更新 3:
you may also try MutationObserver
你也可以试试MutationObserver
回答by Roy J
Use the load eventto wait until all resources have finished loading:
使用load 事件等待所有资源加载完成:
<script>
window.addEventListener("load", function(event) {
// here is the Vue code
});
</script>
DOMContentLoadedis 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,loadis only fired when all the resources (images, stylesheets etc.) are retrieved from the network and available to the browser.
DOMContentLoaded是在解析和呈现 HTML 并构建 DOM 时触发的事件。它通常在应用程序的生命周期中很快就会被触发。另一方面,load只有当所有资源(图像、样式表等)都从网络中检索到并且可供浏览器使用时才会触发。
You can also use the load event for a specific script.
您还可以将 load 事件用于特定脚本。

