【问题标题】:pass vue js component parameter to vuex method-style getter parameter将 vue js 组件参数传递给 vuex 方法样式的 getter 参数
【发布时间】:2020-09-28 21:22:34
【问题描述】:

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 移动到我的商店(并使用操作 => 突变 => 等更新它),但这也不起作用。有什么我想念的想法吗?

【问题讨论】:

    标签: javascript vue.js state vuex getter


    【解决方案1】:

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

    JSFiddle 供您参考(请参阅 javascript 选项卡和控制台输出):https://jsfiddle.net/qb47x2z1/38/

    【讨论】:

    • 我已将 currentType 移至 state,添加了必要的操作 => 突变,但在我的组件 vue 中,如果我写:return this.$store.getters.availablePokemon(currentType),它说 currentType 是未定义,如果我不传递参数,则根本不会呈现列表项
    • @notmynamelastname - 你能发布你更新的代码吗?
    • 我已经编辑了代码。不知道如何在方法风格的 getter 中传递参数....
    • @notmynamelastname - 如果您将 currentType 存储在 Vuex 状态中,则无需再将其传入,只需在调用 getter 之前将其设置为 Vuex 状态即可。不要再向 getter 传递任何东西,因为它应该已经在 Vuex 状态下可用。见我上面的小提琴。
    • @notmynamelastname - 一定要查看适用于 chrome 的 vue 开发工具 - 它可能会为您指出问题所在。尤其是 Vuex 标签:chrome.google.com/webstore/detail/vuejs-devtools/…
    猜你喜欢
    • 2019-02-11
    • 2020-08-09
    • 1970-01-01
    • 2019-05-17
    • 2020-07-22
    • 2018-11-23
    • 2020-11-19
    • 2019-06-11
    • 2020-03-22
    相关资源
    最近更新 更多