2017-08-01 95 views
3

是否可以通過參數mapGettersVue 2 - vuex mapGetters and pass params

我有這個主Vue公司如:

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

this.search通過V模型綁定到輸入字段=「搜索=,在我Vuex比如我有這樣的干將:

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

這一個是工作正常,但我試圖找到一種方式(如果可能)使用mapGetters和傳遞參數可以這樣做

回答

0

如果你想將參數傳入商店,這是最接近的。但是,更好的處理方法是將參數作爲商店的一部分,並將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>

1

這確實可以做到! 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()) 
    } 
    } 
}