简体   繁体   English

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

[英]pass vue js component parameter to vuex method-style getter parameter

New to vuex.刚接触 vuex。 Simple pokemon SPA that should display pokemon by generation and type.应该按世代和类型显示口袋妖怪的简单口袋妖怪 SPA。 I am trying to write a method-style getter that will pass a component's parameter.我正在尝试编写一个方法样式的 getter 来传递组件的参数。 EDIT: moved currentType to state:编辑:将 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)
    }}
}

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.组件方法样式的 getter 无法识别该参数。 I've tried moving the currentType to my store (and updating it with an action => mutation => etc), but that didn't work either.我已经尝试将 currentType 移动到我的商店(并使用 action => mutation => 等更新它),但这也没有用。 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.在架构上,我会将currentType存储在 Vuex state object 中。然后,您可以在 getter function 中引用currentType - 并且 - 还可以在整个应用程序中引用currentType

JSFiddle here for your reference (see javascript tab and console output): https://jsfiddle.net/qb47x2z1/38/ JSFiddle 在这里供您参考(参见 javascript 选项卡和控制台输出): https://jsfiddle.net/qb47x2z1/38/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM