admin管理员组

文章数量:1290925

I added my vue.js in the header but it has an error that says element root can't be found, because I have a div with an id of root.

But when I add it on the body everything works fine.

This is my js code.

new Vue({
     el: '#root'
});

And this is my html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
	
    <script src="/[email protected]/dist/vue.js"></script>
</head>
<body>

<div id="root">

    <task-list>


    </task-list>


</div>


</body>
</html>

I added my vue.js in the header but it has an error that says element root can't be found, because I have a div with an id of root.

But when I add it on the body everything works fine.

This is my js code.

new Vue({
     el: '#root'
});

And this is my html.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
	
    <script src="https://unpkg./[email protected]/dist/vue.js"></script>
</head>
<body>

<div id="root">

    <task-list>


    </task-list>


</div>


</body>
</html>

Share Improve this question edited Jun 9, 2017 at 4:26 Kzy 5085 silver badges14 bronze badges asked Jun 9, 2017 at 1:12 vlad awtsuvlad awtsu 1951 gold badge2 silver badges14 bronze badges 1
  • can you give me a sample of your html – Kzy Commented Jun 9, 2017 at 1:14
Add a ment  | 

3 Answers 3

Reset to default 8

you need to import your vue js library at the bottom part of your body because your #app HTML container needs to be loaded first before it can be analysed by vue js.

<body>

<div id="app">
</div>
<script src="vue.js"></script>

</body>

Hi I didn't see any included js(except for vue package) in your html. But I think the solution is to place your script in footer.

Also if that doesnt work place it inside window.onload

window.onload = function() {
    new Vue({
        el: '#root'
    });
};

you could also use the defer attribute on your script, this will make sure the entire page is loaded before processing the Javascript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    
    <script src="https://unpkg./[email protected]/dist/vue.js" defer ></script>
    <!-- Assuming that you saved your vue code in a seperate file called vue.js -->
    <script src="vue.js" defer ></script>
</head>
<body>

<div id="root">

    <task-list>


    </task-list>


</div>


</body>
</html>

本文标签: javascriptWhy Vuejs needs to be add in the body tagStack Overflow