[Vue warn]:在呈现期间访问了属性“$store”,但未在示例上定义

eiee3dmh  于 2023-03-24  发布在  Vue.js
关注(0)|答案(4)|浏览(212)

我新手和网上商店的项目。我得到了两个错误,我不能以任何方式修复:
1)[Vue warn]:在呈现期间访问了属性“$store”,但未在示例上定义。
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-cataloge.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

3pvhb19x

3pvhb19x1#

如果你把“这个”拿出来就行了

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

您需要在脚本中使用“this”,而不是在模板中。

fxnxkyjh

fxnxkyjh2#

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"
nnt7mjpx

nnt7mjpx3#

您可以使用mapState帮助程序来编写更简洁的代码。
首先导入:

import { mapState } from "vuex";

computed中添加spread操作符以简化语法:

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

现在,您可以在不使用$store.state的情况下使用products

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

zyfwsgd64#

在Vue3中不需要创建store.js。

<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>

相关问题