Javascript [Vue 警告]:找不到元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29484431/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:26:50  来源:igfitidea点击:

[Vue warn]: Cannot find element

javascriptmvvmvue.js

提问by dopatraman

I'm using Vuejs. This is my markup:

我正在使用Vuejs。这是我的标记:

<body>
  <div id="main">
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
  </div>
</body>

This is my code:

这是我的代码:

var main = new Vue({
    el: '#main',
    data: {
        currentActivity: 'home'
    }
})
;

When I load the page I get this warning:

当我加载页面时,我收到此警告:

[Vue warn]: Cannot find element: #main

What am I doing wrong?

我究竟做错了什么?

回答by Arun P Johny

I think the problem is your script is executed before the target dom element is loaded in the dom... one reason could be that you have placed your script in the head of the page or in a script tag that is placed before the div element #main. So when the script is executed it won't be able to find the target element thus the error.

我认为问题是您的脚本在目标 dom 元素加载到 dom 之前执行...一个原因可能是您已将脚本放在页面的头部或放在 div 元素之前的脚本标记中#main. 因此,当脚本执行时,它将无法找到目标元素,从而导致错误。

One solution is to place your script in the load event handler like

一种解决方案是将您的脚本放在加载事件处理程序中,例如

window.onload = function () {
    var main = new Vue({
        el: '#main',
        data: {
            currentActivity: 'home'
        }
    });
}


Another syntax

另一种语法

window.addEventListener('load', function () {
    //your script
})

回答by Su Chuan

I've solved the problem by add attribute 'defer' to the 'script' element.

我通过向 'script' 元素添加属性 'defer' 解决了这个问题。

回答by li bing zhao

I get the same error. the solution is to put your script code before the end of body, not in the head section.

我犯了同样的错误。解决方案是将您的脚本代码放在正文末尾之前,而不是放在 head 部分中。

回答by Tadas Stasiulionis

The simple thing is to put the script below the document, just before your closing </body>tag:

简单的事情是将脚本放在文档下方,就在结束</body>标记之前:

<body>
   <div id="main">
      <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
   </div>
   <script src="app.js"></script>
</body>

app.js file:

app.js 文件:

var main = new Vue({
    el: '#main',
    data: {
        currentActivity: 'home'
    }
});