Bog*_*ngu 16 html javascript vue.js
我正在开发一个Vue组件,它将通过CMS系统放置在多个网站上.我遇到的问题是即使我的js脚本加载顺序是正确的,有时我会收到此错误:
Uncaught ReferenceError: Vue is not defined
at HTMLDocument.<anonymous>
Run Code Online (Sandbox Code Playgroud)
Vue通过cdn加载,它位于组件代码之上.
所有的Vue代码都是这样运行的:
document.addEventListener("DOMContentLoaded", () => {
// here is the Vue code
});
Run Code Online (Sandbox Code Playgroud)
我甚至在DOMContentLoaded事件中添加了一个setTimeout(),但仍然没有做到这一点.
window.onload = function()在所有情况下都不起作用.我还是经常遇到这个错误.脚本加载到正文中.
你知道它可以是另一种方法吗?我想确保在激活Vue代码的那一刻,Vue已加载并准备在页面上初始化.谢谢!
ctf*_*tf0 36
使用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
}
Run Code Online (Sandbox Code Playgroud)
请注意,您可以省略window.addEventListener()它仍然可以工作,但它可能会错过+如果你使用像jquery这样的东西,outerHeight(true)最好在窗口事件中使用它,以确保你得到正确的值.
而不是window.addEventListener('load')还有另一种方式使用,document.readyState所以上面可以
mounted() {
document.onreadystatechange = () => {
if (document.readyState == "complete") {
// run code here
}
}
},
Run Code Online (Sandbox Code Playgroud)
最可靠的方法,到目前为止我已经找到了将使用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
Run Code Online (Sandbox Code Playgroud)
当使用去抖动时更新它会变得棘手,所以一定要测试它b4继续前进.
您也可以尝试MutationObserver
Roy*_*y J 19
使用load事件等待所有资源加载完毕:
<script>
window.addEventListener("load", function(event) {
// here is the Vue code
});
</script>
Run Code Online (Sandbox Code Playgroud)
DOMContentLoaded是解析和呈现HTML并构造DOM时触发的事件.它通常在应用程序的生命周期内快速启动.另一方面,load仅在从网络检索所有资源(图像,样式表等)并且浏览器可用时才触发.
您还可以将load事件用于特定脚本.