Vue 2 - vuex mapGetters并传递参数

时间:2017-08-01 12:18:17

标签: vue.js vuejs2 vuex

是否可以通过 mapGetters 传递参数?

我在主Vue实例中有这个:

computed: {
    filterAuthors() {
        return this.$store.getters.filterAuthors(this.search.toLowerCase());
    }
}

this.search 通过 v-model =" search = 绑定到输入字段,在我的Vuex实例中我有这个getter:

getters: {
    filterAuthors: (state) => (search) => {
        return state.authors.filter((author) => {
            return author.name.toLowerCase().indexOf(search) >= 0;
        })
    }
},

这个工作正常,但我试图找到一种方法(如果可能的话)使用mapGetters并传递参数。可以这样做吗?

2 个答案:

答案 0 :(得分:5)

这确实可以做到! mapGetters只是将this.yourGetterName映射到此。$ store.getters.yourGetterName(参见docs

所以要完成你想要的东西:

import { mapGetters } from 'vuex'

export default {
  // ... the rest of your Vue instance/component
  computed: {
    // Mix your getter(s) into computed with the object spread operator
    ...mapGetters([
      'filteredAuthors'
      // ...
    ]),
    // Create another computed property to call your mapped getter while passing the argument
    filteredAuthorsBySearch () {
      return this.filteredAuthors(this.search.toLowerCase())
    }
  }
}

答案 1 :(得分:1)

如果您确实希望将参数传递到商店,这是您可以做的最接近的事情。但是,处理它的更好方法是将param作为存储的一部分,并将input字段设置为具有相应getter和setter的计算属性以更新状态。然后,您可以使用mapGetter来获得结果。



const { mapGetters } = Vuex

const authorsInput = [{ name: 'Stephen King'}, { name: 'Neal Stephenson'}, { name: 'Tina Fey'}, { name: 'Amy Poehler'}, { name: 'David Foster Wallace'}, { name: 'Dan Brown'}, { name: 'Mark Twain'}]

const store = new Vuex.Store({
  state: {
    srchInput: '',
    authors: authorsInput
  },
  getters: {
    filteredAuthors: (state) => state.authors
      .filter((author) => author
        .name
        .toLowerCase()
        .indexOf(state.srchInput.toLowerCase()) >= 0)
      .map((author) => author.name)
  },
  mutations: {
    UPDATE_SRCH_INPUT: (state, input) => state.srchInput = input
  },
})

new Vue({
  el: '#app',
  store,
   computed: Object.assign({
    srchInput: {
      get () { return store.state.srchInput},
      set (val) { store.commit('UPDATE_SRCH_INPUT', val) } 
    }
  }, mapGetters([
    'filteredAuthors'
  ]))
})

filterAuthors: (state) => (search) => {
        return state.authors.filter((author) => {
            return author.name.toLowerCase().indexOf(search) >= 0;
        })
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.js"></script>
<div id="app">
 <div>
    <input type="text" v-model="srchInput"/>
    <ul>
      <li v-for="author in filteredAuthors">{{author}}</li>
    </ul>
  </div>
</div>
&#13;
&#13;
&#13;