我正在嘗試將我的狀態設定為我使用商店中的 GETTER 從我的 API 獲取的資料。
在mounted()生命周期鉤子期間觸發 GETTER getProducts(),如下所示:
export const getters = {
async getProducts() {
axios.get('/api/products')
.then(res => {
var data = res.data
commit('setProducts', data)
})
.catch(err => console.log(err));
}
}
在 GETTER 中,我嘗試觸發 MUTATION 呼叫setProducts(),如下所示:
export const mutations = {
setProducts(state, data) {
state.products = data
}
}
但是當我運行它時,我收到錯誤ReferenceError: commit is not defined在我的控制臺中。很明顯,出了什么問題觸發了 MUTATION,但在互聯網上連續尋找 2 天后,我仍然找不到任何東西。
我也嘗試替換commit('setProducts', data)為:this.setProducts(data) setProducts(data)
這一切都以錯誤“TypeError:無法讀取未定義的屬性(讀取'setProducts')”而告終
uj5u.com熱心網友回復:
如果您的函式getProduct是在 Vue 組件中定義的,您必須像這樣訪問商店:
this.$store.commit('setProducts', data)
如果您的函式不是在 Vue 組件中定義而是在外部 javascript 檔案中定義,您必須首先匯入您的商店
import store from './fileWhereIsYourStore.js'
store.commit('setProducts', data)
如果您的getters匯出字面上是您商店的 getter 的定義,您可以先使用匯入商店的解決方案,但您應該知道,在 getter 中進行提交顯然不是一個好習慣。您的問題必須有更好的解決方案。
編輯:要回答您的評論,您可以這樣做:
// Your store module
export default {
state: {
products: []
},
mutations: {
SET_PRODUCTS(state, data) {
state.products = data
}
},
actions: {
async fetchProducts(store) {
await axios.get('/api/products')
.then(res => {
var data = res.data
store.commit('SET_PRODUCTS', data)
})
.catch(err => console.log(err));
}
}
}
現在,您可以像這樣在每個組件中獲取產品并填充您的商店:
// A random Vue Component
<template>
</template>
<script>
export default {
async mounted() {
await this.$store.dispatch('fetchProducts')
// now you can access your products like this
console.log(this.$store.state.products)
}
}
</script>
我沒有測驗這段代碼,但應該沒問題。
uj5u.com熱心網友回復:
commit正如您在此處看到的那樣,只有操作在其背景關系中才有。
吸氣劑沒有commit。
否則,你也可以使用mapActions(aka import { mapActions } from 'vuex'),而不是this.$store.dispatch(只是風格問題,最后沒有真正的區別)。
重構您的代碼以執行 Julien 建議的操作是一個很好的解決方案,因為這就是您應該如何使用 Vuex。
Getter 通常用于具有某些具有特定結構的狀態,例如按字母順序排序或類似的。對于公共狀態訪問,請使用常規狀態或mapState幫助程式。

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375511.html
標籤:javascript Vue.js nuxt.js 店铺
上一篇:找到陣列物件的相似值并計算已售出
