将vue js组件参数传递给vuex方法样式的getter参数

问题描述 投票:0回答:1

vuex的新手。简单的神奇宝贝SPA,应该按世代和类型显示神奇宝贝。我正在尝试编写将通过组件参数的方法风格的吸气剂。编辑:将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 =>等更新它),但这也不起作用。有什么想法我想念的吗?

javascript vue.js state vuex getter
1个回答
1
投票

存档,我将currentType存储在Vuex状态对象。然后,您可以在getter函数中引用currentType,并且-还可以引用currentType应用程序范围。

JSFiddle,供您参考:https://jsfiddle.net/qb47x2z1/38/

© www.soinside.com 2019 - 2024. All rights reserved.