问题
I am using vuejs, vuex, and vuetify.
There are 3 files involved I will post the important parts.
Basically I want to display data corresponding to the route parameter. Whenever I use the following in my Product.vue
<h1 class="heading primary--text"> {{ product.partNumber }}</h1>
Nothing on that file loads, and when I check the console I get the following...
Chrome: "TypeError: Cannot read property 'find' of undefined"
Firefox: [Vue warn]: Error in render: "TypeError: state.loadedProducts is undefined"
In this same project I made a vue page that loads all the products on the page using v-for, and one of the getters, just fine.
I am really unsure what is wrong, please help before my hairline disappears.
store.js
getters:{
loadedProducts (state) {
return state.products.sort((productA, productB) => {
return productA.partNumber > productB.partNumber
})
},
loadedProduct (state) {
return (productId) => {
return state.loadedProducts.find((product) => {
return product.partNumber === productId
})
}
}
}
router.js
{
path: '/product/:id',
name: 'Product',
props: true,
component: Product
}
Product.vue
<script>
export default {
name: 'Product',
props: ['id'],
computed: {
product () {
return this.$store.getters.loadedProduct(this.id)
}
}
}
</script>
回答1:
Instead of attempting to access the loadedProducts
via store
, instead access it through the getters themselves. The docs on getters provide an example of accessing other getters within a getter via the second argument.
Getters will also receive other getters as the 2nd argument
loadedProduct (state, getters) {
return (productId) => {
return getters.loadedProducts.find((product) => {
return product.partNumber === productId
})
}
}
Be sure you are setting reasonable defaults for your store properties such as an empty array for products
.
Hopefully that helps!
来源:https://stackoverflow.com/questions/53993012/a-getter-i-made-in-vuex-store-js-is-getting-errors