访问嵌套对象时的Vue警告 [英] Vue warning when accessing nested object

查看:33
本文介绍了访问嵌套对象时的Vue警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么在访问嵌套对象时会收到 Vue 警告.

{{ user.area.name }}

<块引用>

[Vue 警告]:渲染错误:TypeError:无法读取未定义的属性‘名称’"

类型错误:无法读取未定义的属性名称"

只是访问对象没有警告.

{{ 用户名}}

有什么建议吗?

解决方案

这里完全是猜测,但让我们看看我是否正确...

假设您的组件/Vue 实例 data 初始化程序中有这样的东西...

data() {返回 {用户:{}}}

然后您异步填充该对象,例如

mounted() {setTimeout(() => {//setTimeout 只是一个例子this.user = {...this.user,区域: {名称:'富'}}}, 1000)}

如果你的模板有

{{ user.area.name }}

当它在异步任务完成之前开始呈现时,您将尝试访问未定义的 areaname 属性.

示例 ~ http://jsfiddle.net/tL1xbmoj/

<小时>

您的选择是...

  1. 使用不会导致错误的结构初始化您的数据

    data() {返回 {用户:{区域: {名称:空}}}}

    示例 ~ http://jsfiddle.net/tL1xbmoj/1/

  2. 使用条件渲染来防止错误

    {{ user.area.name }}</span>

    示例 ~ http://jsfiddle.net/tL1xbmoj/2/

I am not sure why I get a Vue warning when accessing nested object.

{{ user.area.name }}

[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"

TypeError: Cannot read property 'name' of undefined

Just accessing the object has no warning.

{{ user.name }}

Any advice?

解决方案

Totally guessing here but lets see if I'm right...

Say you've got something like this in your component / Vue instance data initialiser...

data () {
  return {
    user: {}
  }
}

and you then populate that object asynchronously, eg

mounted () {
  setTimeout(() => { // setTimeout is just an example
    this.user = {
      ...this.user,
      area: {
        name: 'foo'
      }
    }
  }, 1000)
}

If your template has

{{ user.area.name }}

when it initially renders before the asynchronous task has completed, you will be attempting to access the name property of area which is undefined.

Example ~ http://jsfiddle.net/tL1xbmoj/


Your options are...

  1. Initialise your data with a structure that won't cause errors

    data () {
      return {
        user: {
          area: { 
            name: null 
          } 
        }
      }
    }
    

    Example ~ http://jsfiddle.net/tL1xbmoj/1/

  2. Use conditional rendering to prevent the error

    <span v-if="user.area">{{ user.area.name }}</span>
    

    Example ~ http://jsfiddle.net/tL1xbmoj/2/

这篇关于访问嵌套对象时的Vue警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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