TypeError:无法读取未定义的属性“

时间:2020-01-30 09:40:53

标签: vue.js vuejs2 nuxt.js

※对不起,我的英语水平很低,因此,如果您听不懂,请随意提问。 我正在与Nuxt开发媒体 我使用由Rails制作的API,该API存储在商品数据中并在Nuxt中显示。 在开发环境中,数据正常显示,但是在生产环境中,我捕获了一个错误

TypeError: Cannot read property 'title' of undefined

它是源代码

<div class="contents-header">  
  <h1>{{posts.title}}</h1>  
</div>  

export default {   

head(){  
  return{  
    title: this.posts.title,  
    meta:[{ hid: 'title', name: 'title', content: this.posts.title }]
  }  

async asyncData({app,params,error}) {  
  const {id} = params;  
  const response  = await axios.get(`https://hogehoge.com/api/v1/posts/${id}`)  
  .catch(err=> {  
  error({  
    statusCode: err.response.status,  
    message: err.response.data.message,  
  });  
  return err.response;  
  });  
  const posts = JSON.parse(response.data)  
  return {posts};  
},  
} 

1 个答案:

答案 0 :(得分:0)

您应将data添加到props(或posts)属性posts中,因为export default { data(){ posts: [], } } 在vue组件范围内不存在:

posts

然后在代码方法中,您可以像这样设置this.posts = response.data; 数组:

overflow: TextOverflow.xxxx