Sas*_*sha 11 vue.js vuex vuejs2
是否可以使用mapGetters传递参数?
我在主Vue实例中有这个:
computed: {
filterAuthors() {
return this.$store.getters.filterAuthors(this.search.toLowerCase());
}
}
Run Code Online (Sandbox Code Playgroud)
this.search通过v-model ="search =绑定到输入字段,在我的Vuex实例中我有这个getter:
getters: {
filterAuthors: (state) => (search) => {
return state.authors.filter((author) => {
return author.name.toLowerCase().indexOf(search) >= 0;
})
}
},
Run Code Online (Sandbox Code Playgroud)
这个工作正常,但我试图找到一种方法(如果可能的话)使用mapGetters并传递参数.可以这样做吗?
确实可以做到!mapGetters只是将this.yourGetterName映射到this。$ 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())
}
}
}
Run Code Online (Sandbox Code Playgroud)
kev*_*guy -1
如果您确实想将参数传递到商店,这是您可以做的最接近的事情。然而,更好的处理方法是将参数也作为存储的一部分,并将字段设置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'
]))
})Run Code Online (Sandbox Code Playgroud)
filterAuthors: (state) => (search) => {
return state.authors.filter((author) => {
return author.name.toLowerCase().indexOf(search) >= 0;
})
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13926 次 |
| 最近记录: |