Vue.js v-for not working
Asked Answered
E

3

6

I'm trying Vue.js out but I am running into a problem. I am following a tutorial over at Laracasts but my v-for isn't working.

HTML:

<div id="root">
  <ul>
    <li v-for="name in names" v-text="name"></li>
  </ul>

  <input type="text" v-model="newName">
  <button @click="addName">Add Name</button>
</div>

JS:

new Vue({
    el: '#root',
    data: {
        newName: '',
      names: ['John', 'Mike']
    }
    methods: {
        addName() {
        this.names.push(this.newName);
        this.newName = '';
      }
    }
})

Fiddle: https://jsfiddle.net/4pb1f4uq/

If it helps, the link to the Laracast with episode: https://laracasts.com/series/learn-vue-2-step-by-step/episodes/4?autoplay=true

Epoch answered 19/4, 2017 at 8:35 Comment(1)
It may help if you read the output if your compiler or even in you console. It would show you that you've forgotten to place a comma after defining the data.Send
K
8

You are missing the comma after the data object:

data: {
  newName: '',
  names: ['John', 'Mike']
},  // comma here
Khoisan answered 19/4, 2017 at 8:42 Comment(1)
Well, this works within my JSfiddle, but not my own site... this is really wierd.Epoch
D
2

You have a simple syntax error - a comma is missing between the "data" and "methods" objects:

data: {
  newName: '',
  names: ['John', 'Mike']
}, //this comma was missing

This version of your fiddle adds it, and shows it working: https://jsfiddle.net/4pb1f4uq/1/

You can detect this kind of thing easily yourself by checking for errors in your browser's console (press F12). It will highlight the syntax error and usually you can click on the error and be taken to the offending line of code.

Dawn answered 19/4, 2017 at 8:44 Comment(0)
B
0

v-for was not working for me, for dynamically added elements in object. Turned out there some reactivity issue. And element to array should be added like this

this.$set(this.files, key, file)
Bolme answered 24/1, 2023 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.