根据路线显示来自Vuex存储在组件中的数据

我在Vuex存储中有以下数据:

 state: {
    news: [
      { id: 1,  title: "placeholder", text: "Lorem ipsum doloret imes", date: "20-01-2020", type: "management" },
      { id: 2,  title: "Revenue", text: "Lorem ipsum doloret imes", date: "20-01-2020",  type: "management"  }]
}

我想根据route中使用的ID在组件中显示此数据:

 {path: '/news/:id',
   component: () => import('../views/NewsDetail.vue'), 
   props: true
  }

在我的NewsDetail.vue组件中,我尝试像这样检索数据:

<template>
 <p class="display-1 text--primary">{{display.type}}</p>
</template>

<script>
 data () {
    return {
      display: newsId
    }
  },
  created () {
    const newsId = this.$store.state.news.find((newsId) => { return newsId.id == this.$route.params.id})
  }
</script>

但是我得到一个错误,即未定义newsId,并且已定义但从未使用过... 如何根据路由ID(应该与存储中条目的ID相匹配)显示Vuex存储中的数据?

评论
  • zvelit
    zvelit 回复

    Your newsId constant is defined in the created() method and only exists within that scope. It is deleted as soon as the function returns. That's why you're getting the error message--because the const isn't used inside the function, and it's not available to be used anywhere else.

    I suggest you create an id prop in your NewsDetail component, which will automatically be populated with the ID param. Then use a computed property to fetch the appropriate data from the store.

  • 龙舌兰
    龙舌兰 回复

    “未定义newsId的错误”

    所以你想要的是Vuex吸气剂

    <script>
      import { mapGetters } from 'vuex'
    
      computed: {
      ...mapGetters([
        news
      ]),
    
      newsId() {
        return this.news.find((newsId) => { return newsId.id == this.$route.params.id})
      }
    }
    

    就是这样或将newsId添加到数据对象

    <script>
       data () {
         return {
           newsId: '',
           display: newsId
         }
       },
    
      created () {
        this.newsId = this.$store.state.news.find((newsId) => { return newsId.id == 
        this.$route.params.id})
    }
    </script>