【问题标题】:For loop for VueJS?VueJS的for循环?
【发布时间】:2020-10-09 06:16:31
【问题描述】:

我试过了:

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

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

但它说

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

我也试过了:

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

但它没有输出任何东西,也没有显示任何错误。 有什么帮助吗?非常感谢!

更新:

这是this.questions。它是一个对象数组:

data: {
    questions: [
        {'name': 'etc', 'content': 'etc'},
        {'name': 'etc2', 'content': 'etc2'},
    ],
},

【问题讨论】:

  • 什么是this.questions?它似乎不是一个数组或任何可访问的东西。
  • 你应该传递函数而不是调用它:this.questions.forEach(this.get_choices)
  • @HaoWu forEach 未被识别为存在于 this.questions 上的方法。传递函数引用无助于解决这个问题。
  • @HaoWu 是的,我试过了,但同样的错误。
  • @VLAZ 你是对的,最重要的是......确保this.questions 是一个数组,然后传递我提到的函数

标签: javascript vue.js


【解决方案1】:

你需要从你的函数调用中删除括号,你只需要引用

this.questions.forEach(this.get_choices)

【讨论】:

  • 这是问题问题的正确原因。此外,我还要注意,您必须将数据作为函数返回一个对象。原因是 vue 反应性系统。 data() { return { questions: [ /* ... */ ]}}
  • @ChopTRAN 好吧,如果您使用 CDN 并且没有组件,这不是必须的,但是是的,将它用作函数总是更好vuejs.org/v2/guide/components.html#data-Must-Be-a-Function
【解决方案2】:

你需要传递对象来作为函数

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

或者你也可以这样做

this.questions.forEach(this.get_choices)

【讨论】:

    猜你喜欢
    • 2020-04-01
    • 2020-03-23
    • 2020-01-31
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多