I’m trying to use v-for to generate a number of divs, but no matter how many ways I have tried (I also have tried using it to iterate over a list, doesn’t work either), the v-for is just not working as it should, and alway turn the line into a comment when it runs.
No error shown in console.
here is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
<!-- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>
<div id="game_board_block" v-for="num in 10">{{num}}</div>
<script language="JavaScript" src="game.js"></script>
</body>
</html>
I have tried loading Vue by either of the https link, both work for other Vue directives(v-if, v-show etc.), so it shouldn’t be the problem with loading Vue.
and here is the code in my game.js
var game_board_block = new Vue({
el: "#game_board_block",
data: {
n: 5,
list1: [5, 2, 0]
}
});
** By the way, why do I must put my own js script which bound the div to a Vue instance below the html code of that div? I’m very new to Vue, I just know this can work, but I don’t know why it works, I have tried to put it before the html code bounded to it, or in title area but none of them would work. And this is a little counterintuitive for me, I thought it would make more sense if I bound the element first before using it? Or is it the case that before the html code, that html element can be considered as "not exist", so there is no way to bound it to a Vue instance?
here is how the html elements look like when I open inspect elements of the browser:
img
I then tried replacing
<div id="game_board_block" v-for="num in 10">{{num}}</div>
with
<div id="game_board_block">
<div v-for="num in 10">{{num}}</div>
</div>
and it does work as I expected, but I’m not sure why exactly that it can work now? Is it that v-for can’t be used in the same element that bound to a Vue instance? It can only be in the child node of an element that bound to a Vue instance?
2
Answers
you can’t do anything weird with vue root even though i haven’t tried it with vue3 root but i’m sure vue 2 requires a component to have only 1 node at root
When you do:
You’re trying to loop & create multiple div elements with the same id. Since your Vue instance is linked to #game_board_block, there should only be one element with that id.
This is why this works:
Above, your Vue instance is able to mount on the div with id game_board_block.
Here’s the official documentation for more details: https://v2.vuejs.org/v2/guide/instance.html#Creating-a-Vue-Instance