[英]pass vue js component parameter to vuex method-style getter parameter
剛接觸 vuex。 應該按世代和類型顯示口袋妖怪的簡單口袋妖怪 SPA。 我正在嘗試編寫一個方法樣式的 getter 來傳遞組件的參數。 編輯:將 currentType 移至 state:
//Vuex.Store
state: {
pokemon: [],
currentType: 'all'
},
getters:{
availablePokemon: (state) => (currentType) => {
if(!currentType || currentType === 'all'){
return state.pokemon
}else{
return state.pokemon.filter(pokemon => {
//some api objects have two types
if(pokemon.types.length === 2){
if(pokemon.types[0] == currentType || pokemon.types[1] == currentType){
return true
}
}else if(pokemon.types[0] == currentType){
return true
}
})
}
},
mutations:{
changeType(state, type){
state.currentType = type
}
},
actions:{
updateType(context, type){
context.commit('changeType', type)
}}
}
編輯:
//Pokemon.vue
<select name="type" id="type" @change="updateType($event.target.value)">
<option v-for="(type, index) in types"
:key="index"
:value="type">{{ type }}</option>
</select>
<li v-for="(pokemon, index) in allPokemon"
:key="index">
{{ pokemon.name }}
</li>
export default {
data(){
return{
types: ['all', 'bug', 'dragon'],
}
},
computed: {
allPokemon(){
//this fails, says currentType is undefined
return this.$store.getters.availablePokemon(currentType)
}
},
methods: {
updateType(type){
this.$store.dispatch('updateType', type)
}
}
組件方法樣式的 getter 無法識別該參數。 我已經嘗試將 currentType 移動到我的商店(並使用 action => mutation => 等更新它),但這也沒有用。 有什么想法我想念的嗎?
在架構上,我會將currentType
存儲在 Vuex state object 中。然后,您可以在 getter function 中引用currentType
- 並且 - 還可以在整個應用程序中引用currentType
。
JSFiddle 在這里供您參考(參見 javascript 選項卡和控制台輸出): https://jsfiddle.net/qb47x2z1/38/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.