使VueJS表达式可以调试

时间:2018-01-29 09:45:58

标签: debugging vue.js

我的vue js数据有一些数组,在模板中我试图使用v-for循环来渲染它们。

类似的东西:

<tr v-for="d in [0,1,2,3]"><td>{{data.people[d].name}}</td></tr>
<tr v-for="d in [0,1,2,3]"><td>{{data.places[d].name}}</td></tr>
<tr v-for="d in [0,1,2,3]"><td>{{data.orders[d].id}}</td></tr>
<tr v-for="d in [0,1,2,3]"><td>{{data.other_array[d].id}}</td></tr>
<tr v-for="d in [0,1,2,3]"><td>{{data.more_array[d].som_property}}</td></tr>

我收到的错误如下:

TypeError: Cannot read property '0' of undefined
    at eval (eval at createFunction (vue.js:10518), <anonymous>:2:3084)
    at Proxy.renderList (vue.js:3666)
    at Proxy.eval (eval at createFunction (vue.js:10518), <anonymous>:2:2915)
    at Vue$3.Vue._render (vue.js:4465)
    at Vue$3.updateComponent (vue.js:2765)
    at Watcher.get (vue.js:3113)
    at new Watcher (vue.js:3102)
    at mountComponent (vue.js:2772)
    at Vue$3.$mount (vue.js:8416)
    at Vue$3.$mount (vue.js:10777)
logError @ vue.js:1719
globalHandleError @ vue.js:1710
handleError @ vue.js:1699
Vue._render @ vue.js:4467
updateComponent @ vue.js:2765
get @ vue.js:3113
Watcher @ vue.js:3102
mountComponent @ vue.js:2772
Vue$3.$mount @ vue.js:8416
Vue$3.$mount @ vue.js:10777
Vue._init @ vue.js:4557
Vue$3 @ vue.js:4646
(anonymous) @ astromap.html:291

我明白这意味着我的某个阵列的某个地方没有被初始化,我会找到那个数组,我也知道我可以用守卫编写并使用v-if。

困扰我的是上面的堆栈跟踪似乎毫无用处。

我的Q是:

有没有更好的方法来编写这样的模板,而不是防止它们失败,但是当它们失败时我会得到更具指示性的输出?

或者,是否有任何其他调试魔法(例如某些lastParsedExpression秘密变量),我可以在调试控制台中使用它来告诉我失败的表达式是什么?

更新:经过编辑,强调错误可能发生在多个地方。

2 个答案:

答案 0 :(得分:0)

我认为你要找的是ErrorBoundary

Vue.component('ErrorBoundary', {
  data: () => ({ error: null }),
  errorCaptured (err, vm, info) {
    this.error = `${err.stack}\n\nfound in ${info} of component`
    return false
  },
  render (h) {
    if (this.error) {
      return h('pre', { style: { color: 'red' }}, this.error)
    }
    // ignoring edge cases for the sake of demonstration
    return this.$slots.default[0]
  }
})

<error-boundary>
  <another-component/>
</error-boundary>

答案 1 :(得分:0)

v-for数组中的第一项是0。错误说明:

Cannot read property '0' of undefined

您正试图访问0

上的媒体资源people
people[d].name

您在哪里定义了people

错误告诉您未定义对象,而不是数组。

相关问题