vue:未捕获的类型错误:无法读取未定义的属性... [英] vue: Uncaught TypeError: Cannot read property ... of undefined

查看:117
本文介绍了vue:未捕获的类型错误:无法读取未定义的属性...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 vue@2.1.3 和 vue 官方 webpack 模板 来构建一个应用.

在本地开发时,经常看到警告Uncaught TypeError:Cannot read property ... of undefined,但是HTML可以渲染成功.但是,当使用 npm run build 命令将 HTML 部署到 Netlify 时,它无法呈现.所以我必须认真对待这个警告.

我从这里了解到它是因为呈现组件时数据不完整,但例如从 API 加载."解决方案是仅在加载数据后才使用 v-if 渲染模板的那部分."

有两个问题:

  1. 我尝试将 v-if 包裹在多个生成警告的语句中,但我个人认为这个解决方案很冗长.有什么巧妙的方法吗?
  2. 本地开发中的警告"在生产中变成了致命错误"(HTML 无法呈现).如何使它们相同?例如它们都发出警告或错误?

解决方案

只需在模板中依赖于 AJAX 调用的所有元素的公共父级上使用 v-if,而不是围绕每个元素.

所以,而不是像这样:

<h1 v-if="foo.title">{{ foo.title }}</h1><p v-if="foo.description">{{ foo.description }}</p>

<模板 v-if="foo"><h1>{{foo.title}}</h1><p>{{ foo.description }}</p>

I'm using vue@2.1.3 and the vue official webpack template to build an app.

When developing locally, I often see the warning Uncaught TypeError: Cannot read property ... of undefined, but the HTML can be rendered successfully. However, the HTML can't be rendered when it's deployed to Netlify with npm run build command. So I have to treat this warning seriously.

I learned from here that it's because "the data is not complete when the component is rendered, but e.g. loaded from an API." and the solution is to "use v-if to render that part of the template only once the data has been loaded."

There are two questions:

  1. I tried wrap v-if around multiple statements that's generating the warning but personal I think this solution is verbose. Is there a neat approach?
  2. "warnings" in local development turn into "fatal errors"(HTML can't be rendered) in production. How to make them the same? e.g. both of them issue warnings or errors?

解决方案

Just use v-if on a common parent to all the elements in your template relying on that AJAX call, not around each one.

So instead of something like:

<div>
  <h1 v-if="foo.title">{{ foo.title }}</h1>
  <p v-if="foo.description">{{ foo.description }}</p>
</div>

Do

<div>
  <template v-if="foo">
    <h1>{{ foo.title }}</h1>
    <p>{{ foo.description }}</p>
  </template>
</div>

这篇关于vue:未捕获的类型错误:无法读取未定义的属性...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆