How to console.log an item inside a v-for loop in Vue
Asked Answered
O

3

13

I can't figure out how to do a console.log to see what item is in the ul as its being passed.

 <div v-for="(item, index) in todos" :key="index">
     <ul v-if="item" :load="console.log(item)">
         <li v-for="(value, key) in item" :key="key">
            <label v-bind:for="key">{{ key }}</label>
            <div v-bind:id="key">{{ value }}</div>
         </li>
     </ul>
 </div>

 var vm = new Vue({
    el: '#components-demo',
    data: {
        todos: [
            newData
        ]
    }
 })
Opposable answered 7/1, 2019 at 15:57 Comment(3)
it should just display, you should just look at what HTML the template is outputting, I think console logging would be a bit of overkill hereProper
i guess i need for future endeavors as well, i need to know how to do itOpposable
a similar question: #51080947Arpeggio
W
24

you should define a method like :

  <ul v-if="item" :load="log(item)">

in your script :

var vm = new Vue({
  el: '#components-demo',
  data: {
    todos: [
      newData
    ]
  },
  methods: {
    log(item) {
      console.log(item)
    }
  }
})
Wolsky answered 7/1, 2019 at 15:59 Comment(1)
to use globally, add Vue.prototype.log = console.log; in main.jsMussorgsky
H
7

I usually wrap the value I'm debugging in <pre>{{ myData }}</pre> like this:

<div v-for="(item, index) in todos" :key="index">
     <pre>{{ item }}</pre>
     <ul v-if="item" :load="item">
         <li v-for="(value, key) in item" :key="key">
            <label v-bind:for="key">{{ key }}</label>
            <div v-bind:id="key">{{ value }}</div>
         </li>
     </ul>
 </div>

But you can also use console if you pass it into t he template context during create

 <div v-for="(item, index) in todos" :key="index">
     <ul v-if="item" :load="console.log(item)">
         <li v-for="(value, key) in item" :key="key">
            <label v-bind:for="key">{{ key }}</label>
            <div v-bind:id="key">{{ value }}</div>
         </li>
     </ul>
 </div>

 var vm = new Vue({
    el: '#components-demo',
    data: {
        todos: [
            newData
        ]
    },
    created() {
      this.console = window.console;
    }
 })
Hopeless answered 7/1, 2019 at 17:22 Comment(0)
C
1

Similar to Daniel's answer, but you can simply reference console in data object

data(){
  return {
  console, //ES6
  ...
  }
}
Critic answered 23/10, 2019 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.