我希望通过单击搜索按钮并键入搜索输入,按标题过滤任务数组。我使用Vuex,并通过commit将search参数传递到mutation中,以获得filter初始列表。但列表没有呈现。还是Vuex需要通过Actions来完成?
子组件
<template>
<div class="tasks">
<input
type="text"
v-model="search"
@keypress.enter="searchTask"
placeholder="search task"
/>
<button @click="searchTask" class="btn">Search</button>
<Task v-for="task in tasks" :key="task.id" :task="task" />
</div>
</template>
<script>
export default {
data() {
return {
search: '',
};
},
computed: {
tasks() {
return this.$store.state.tasks;
},
},
created() {
this.$store.dispatch('getTasks').then((data) => console.log(this.tasks));
},
methods: {
searchTask() {
this.$store.commit('searchTask', this.search);
},
},
};
</script>
店铺
export const state = () => ({
tasks: [],
});
export const actions = {
async getTasks(context) {
const res = await fetch('https://dummyjson.com/todos');
if (res.ok) {
let result = await res.json();
context.commit('setTasks', result.todos);
}
return res.ok;
},
};
export const mutations = {
setTasks(state, data) {
state.tasks = data;
},
searchTask(state, search) {
return state.tasks.filter((t) => {
return t.todo.toLowerCase().includes(search); // isn't filtering the iniiial array
});
},
};
1条答案
按热度按时间mnowg1ta1#
尝试将
tasks
设置为筛选数组,而不是返回: