如何在Vuex商店中搜索标题?

3pvhb19x  于 2023-05-07  发布在  Vue.js
关注(0)|答案(1)|浏览(99)

我希望通过单击搜索按钮并键入搜索输入,按标题过滤任务数组。我使用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
    });
  },
};
mnowg1ta

mnowg1ta1#

尝试将tasks设置为筛选数组,而不是返回:

searchTask(state, search) {
  state.tasks = state.tasks.filter((t) => {
    return t.todo.toLowerCase().includes(search.toLowerCase());     
  });
},

相关问题