【问题标题】:Nuxt.js | Cannot read property of returned object of computed methodNuxt.js |无法读取计算方法返回对象的属性
【发布时间】:2020-03-27 21:38:18
【问题描述】:

我使用计算方法来动态分配变量并加载我的页面。我可以显示整个对象。但是我无法显示单个属性。错误信息说:

无法读取未定义的属性“标题”

这就是我的“页面”组件的代码(“_id.vue”):

> <template>
>     <div class="container">
>       <h1>{{ post }}</h1>
>     </div> </template> <script>   import axios from 'axios';
>     export default {
>         data() {
>           return{
>             id: this.$route.params.id,
>             posts:[]
>           }
>         },
>       computed: {
>           post(){
>             console.log(this.id);
>             return this.posts.find(post => post.id == this.id)
>         }
>       },
>     async created() {
>         await axios.get("https://jsonplaceholder.typicode.com/posts?_limit=3")
>               .then(res => this.posts = res.data)
>               .catch(err => alert(err));
>       }
>     } </script>
> 
> <style scoped>
> 
> </style>

众所周知,我会在页面上显示整个对象。如果我将 h1 标签更改为:

<h1>{{ post.title }}</h1>

显示上述错误信息。 你能帮我解决这个问题吗?

【问题讨论】:

  • 如果您将created 视为普通代码,为什么还要使用async?...而不是axios,我使用的是fetch,但see the result here

标签: vue.js nuxt.js


【解决方案1】:

尝试条件渲染:

<h1 v-if="post.title">{{ post.title }}</h1>

【讨论】:

  • v-if="post" 解决了这个问题。但是,这样的解决方案在职业发展中是否可以接受?
  • @JarekBernatowicz 这是最好的方法,也是可以接受的
  • 我很奇怪为什么 vueschool.io 上没有提到它
  • 当然,但是当post.title 不存在时,您也可以进行条件渲染,而v-else 指令显示为post not found。我的意思是你可以在加载时使用一些 suspense 微调器,其他用于你的 post 并且没有结果时
猜你喜欢
  • 2020-08-06
  • 2018-11-08
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多