[Vue 警告]:属性"$store"在渲染期间被访问,但未在实例上定义



我是网店的新手和制作项目。我有两个错误,我无论如何都无法修复:

1( [Vue warn]:属性"$存储";在渲染期间访问了,但未在实例上定义。

2( 未捕获的类型错误:无法读取未定义(读取"state"(的属性

Store.js

import { createStore } from 'vuex'
import axios from "axios";
const store = createStore({
state:{
products:[]
},
mutations:{
SET_PRODUCTS_TO_STATE:(state,products)=>{
state.products = products;
}
},
actions:{
GET_PRODUCTS_FROM_API({commit}) {
return axios('http://localhost:3000/products',{
method:"GET"
})
.then((products) =>{
commit('SET_PRODUCTS_TO_STATE',products.data);
return products;
})
.catch((error)=>{
console.log(error)
return error;
})
}
},
getters:{
PRODUCTS(state){
return state.products;
}
}
});
export default store;

v目录.vue

<template>
<div class = 'v-catalog'>
<h1>Catalog</h1>
<div class ="v-catalog__list">
<v-catalog-item
v-for="product in this.$store.state.products"
:key="product.article"
v-bind:product_data="product"
@sendArticle="showChildArticleInConsole"
/>
</div>
</div>
</template>

存储库:https://github.com/BIGBASEDFLOPPA/Project1

如果您将;这个";它将工作

v-for="product in $store.state.products"

您需要使用";这个";在脚本中,但不在模板中。

Vue3.x,您应该在someItem.vue中导入存储在您的情况下,以下代码:

import { useStore } from 'vuex';
export default {
setup(){
let store = useStore()
let products = store.state.products
return {
products
}
}
}
// use products in template
v-for="product in products"

您可以使用mapState助手来编写更干净的代码。

首次导入:

import { mapState } from "vuex";

将其添加到computed内部并使用排列运算符来简化语法:

computed: {
...mapState(['products']),
},

现在您可以在没有$store.state:的情况下使用products

<v-catalog-item v-for="product in products" ...

您不需要在Vue 3中创建store.js。在文件v-catalog.vue中,您必须编写以下代码

<template>
<div class = 'v-catalog'>
<h1>Catalog</h1>
<div class ="v-catalog__list">
<v-catalog-item
v-for="product in products"
:key="product.article"
v-bind:product_data="product"
@sendArticle="showChildArticleInConsole"
/>
</div>
</div>
</template>
<script>
import vCatalogItem from './v-catalog-item'
import axios from "axios";
export default {
components: {
vCatalogItem
},
name: "v-catalog",
data() {
return {
products: []
}
},
async created() {
try {
const res = await axios.get(`http://localhost:3000/products`);
this.products = res.data;
} catch (e) {
console.error(e);
}
}
}
</script>

相关内容

  • 没有找到相关文章