首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将vue js组件参数传递给vuex方法样式的getter参数

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

Stack Overflow用户
提问于 2020-06-10 00:10:17
回答 1查看 455关注 0票数 0

vuex新手。简单的精灵宝可梦SPA,应按代和类型显示精灵宝可梦。我正在尝试编写一个方法风格的getter,它将传递组件的参数。编辑:将currentType移至状态:

代码语言:javascript
复制
//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)
    }}
}

编辑:

代码语言:javascript
复制
//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移动到我的商店(并用一个动作=>突变=>等来更新它),但也不起作用。知道我错过了什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-10 00:19:23

从体系结构上讲,我将currentType存储在Vuex状态对象中。然后,您可以在getter函数中引用currentType,也可以在整个应用程序中引用currentType

这里有供您参考的JSFiddle (参见javascript选项卡和控制台输出):https://jsfiddle.net/qb47x2z1/38/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62287009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档