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移到我的商店(并使用action => mutation =>等更新它),但这也不起作用。有什么想法我想念的吗?
答案 0 :(得分:1)
建筑学上,我将currentType
存储在
Vuex状态对象。然后,您可以在getter函数中引用currentType
-并且-还可以引用整个应用程序中的currentType
。
JSFiddle,供您参考(请参见javascript标签和控制台输出):https://jsfiddle.net/qb47x2z1/38/