Home > OS >  Iterate through many div classes and initilize vue.js
Iterate through many div classes and initilize vue.js

Time:10-16

I am starting to learn Vue.js by creating a simple project - I am creating this simple app where I want to list many todo list items.

My html structure would be something like this:

<div id="todo-list-1" class="todo-list"></div>
<div id="todo-list-2" class="todo-list"></div>
<div id="todo-list-3" class="todo-list"></div>

and my main.js

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  el: '#todo-list-1',
  render: h => h(App)
})

App.vue

<template>
  <div>
    <h2>Vue Test</h2>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

how can I iterate through my elements dynamically so I dont have to create them manually?

new Vue({
  el: '#todo-list-1',
  render: h => h(App)
})
new Vue({
  el: '#todo-list-2',
  render: h => h(App)
})
new Vue({
  el: '#todo-list-3',
  render: h => h(App)
})

I want to create one template but render different lists for my todo list. I cant have one id class "app", I want to have multiple instance of these so I can use them in different places with different data.

CodePudding user response:

You can use querySelectorAll to loop over you lists and define new Vue instance

document.querySelectorAll('.todo-list').forEach(list => {
   new Vue({
     el: `#${list.id}`,
     render: h => h(App)
   })
})
  • Related