0

I tried this:

get_choices: function (item, index){
    console.log(item)
},

this.questions.forEach(this.get_choices())

But it says

Error in mounted hook: "TypeError: this.questions.forEach is not a function"

I also tried:

for(question in this.questions){
    console.log(question)
}

But it didn't output anything, it didn't also displayed any error. Any help? Thanks a lot!

UPDATE:

Here's the this.questions. It is an array of objects:

data: {
    questions: [
        {'name': 'etc', 'content': 'etc'},
        {'name': 'etc2', 'content': 'etc2'},
    ],
},
9
  • 1
    What is this.questions? It doesn't appear to be an array or anything foreachable. Commented Oct 9, 2020 at 6:17
  • You should pass the function instead of calling it: this.questions.forEach(this.get_choices) Commented Oct 9, 2020 at 6:17
  • @HaoWu forEach isn't recognised as a method that exists on this.questions. Passing the function reference wouldn't help with that problem. Commented Oct 9, 2020 at 6:18
  • @HaoWu Yes I tried it but the same error. Commented Oct 9, 2020 at 6:18
  • @VLAZ You're right, on top of that... Make sure this.questions is an array and then pass the function as I mentioned Commented Oct 9, 2020 at 6:19

2 Answers 2

2

You need to remove the paranthesis from your function call, you just need the reference

this.questions.forEach(this.get_choices)
Sign up to request clarification or add additional context in comments.

2 Comments

This is the correct cause of the question problem. In addition, I would also note that you must have your data as a function return an object. The reason is the vue reactivity system. data() { return { questions: [ /* ... */ ]}}
@ChopTRAN well it isnt necessery a must if you use CDN and have no components, but yea its always better to use it as a function vuejs.org/v2/guide/components.html#data-Must-Be-a-Function
0

you need to pass the object to function as

this.questions.forEach((item , index) =>{
      this.get_choices(item , index)
 })

or you can also do like

this.questions.forEach(this.get_choices)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.