vuex新手。简单的精灵宝可梦SPA,应按代和类型显示精灵宝可梦。我正在尝试编写一个方法风格的getter,它将传递组件的参数。编辑:将currentType移至状态:
//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移动到我的商店(并用一个动作=>突变=>等来更新它),但也不起作用。知道我错过了什么吗?
发布于 2020-06-10 00:19:23
从体系结构上讲,我将currentType存储在Vuex状态对象中。然后,您可以在getter函数中引用currentType,也可以在整个应用程序中引用currentType。
这里有供您参考的JSFiddle (参见javascript选项卡和控制台输出):https://jsfiddle.net/qb47x2z1/38/
https://stackoverflow.com/questions/62287009
复制相似问题