我正在嘗試制作產品詳細資訊頁面。詳細資訊頁面名為 _id。打開時,id 將替換為產品 id。在打開頁面時,狀態設定為從 api 獲取的資料。
之后,我嘗試使用一個計算屬性,該屬性參考名為 getProduct() 的 getter this.$route.params.id,在有效負載中帶有一個 id ( )。
這是我的 _id.vue 的樣子:
methods: {
...mapActions("products", ["fetchProducts",]),
...mapGetters("products", ["getProduct",]),
},
async mounted() {
this.fetchProducts()
},
computed: {
product() {
return this.getProduct(this.$route.params.id)
}
}
這是我名為 products.js 的商店檔案的樣子:
import axios from "axios"
export const state = () => ({
producten: []
})
export const mutations = {
setProducts(state, data) {
state.producten = data
}
}
export const getters = {
getProduct(state, id) {
console.log(id)
return state.producten.filter(product => product.id = id)
}
}
export const actions = {
async fetchProducts({ commit }) {
await axios.get('/api/products')
.then(res => {
var data = res.data
commit('setProducts', data)
})
.catch(err => console.log(err));
}
}
有效的是創建狀態,但是當我嘗試使用 getter 時出現問題。正如你所看到的,我 console.log() 是給它的 id。其中記錄以下內容:
![Nuxt 存盤 getter 不起作用,賦予有效載荷的 ID 不是整數 錯誤:[vuex] 不要在突變處理程式之外改變 vuex 存盤狀態](https://img.uj5u.com/2021/12/14/d9ac6643cb874aef86b5e3c2a8cc41ee.png)
我也收到錯誤:client.js?06a0:103 錯誤:[vuex] 不要在變異處理程式之外改變 vuex 存盤狀態。
據我所知,我沒有做什么?
**注意:**這些錯誤的記錄與我的狀態陣列的長度一樣多。
uj5u.com熱心網友回復:
來自Vuex 檔案:
Vuex 允許我們在 store 中定義“getter”。您可以將它們視為商店的計算屬性。與計算屬性一樣,getter 的結果根據其依賴項進行快取,并且僅在其某些依賴項發生更改時才會重新評估。
像computed,getters不支持有引數。
但是有一種方法可以對 getter 進行“方法式訪問”:https : //vuex.vuejs.org/guide/getters.html#property-style-access
您還可以通過回傳函式將引數傳遞給 getter。當您要查詢存盤中的陣列時,這特別有用:
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
請注意,通過方法訪問的 getter 將在您每次呼叫它們時運行,并且不會快取結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/380336.html
上一篇:Vue:按特定順序執行兩個方法
