Reputation: 3754
I have the following data in Vuex store:
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" }]
}
I want to display this data in the component based on the id used in route:
{path: '/news/:id',
component: () => import('../views/NewsDetail.vue'),
props: true
}
In my NewsDetail.vue component I try to retrieve the data like this:
<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>
But I get error that newsId is not defined and that it is defined but never used... How can I display the data from the vuex store based on route id (that should be matching the id of the entry in store)?
Upvotes: 0
Views: 882
Reputation: 1209
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.
Upvotes: 0
Reputation: 3940
'error that newsId is not defined'
so what you want is vuex getters
<script>
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
news
]),
newsId() {
return this.news.find((newsId) => { return newsId.id == this.$route.params.id})
}
}
it's either that or adding newsId to the data object
<script>
data () {
return {
newsId: '',
display: newsId
}
},
created () {
this.newsId = this.$store.state.news.find((newsId) => { return newsId.id ==
this.$route.params.id})
}
</script>
Upvotes: 1