New to vuex. Simple pokemon SPA that should display pokemon by generation and type. I am trying to write a method-style getter that will pass a component's parameter. EDIT: moved currentType to 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)
}}
}
EDIT:
//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)
}
}
The component method-style getter doesn't recognize the parameter. I've tried moving the currentType to my store (and updating it with an action => mutation => etc), but that didn't work either. Any ideas what I'm missing?
Architecturally, I'd store the currentType
in the Vuex state object. Then, you can reference the currentType
in the getter function - and - also reference the currentType
app wide.
JSFiddle here for your reference (see javascript tab and console output): https://jsfiddle.net/qb47x2z1/38/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.