如何从子组件中的过滤器过滤父组件中的数组

时间:2019-06-01 00:07:32

标签: vuejs2 vue-component

我有一个父组件,可以对一组对象进行v-for。我有一个子组件,该子组件显示可能的过滤器列表,以对父列表进行过滤。选择过滤器后,我正在使用event bus发出消息。我似乎无法拼凑而成。我喜欢这个想法是一个计算属性,但是如何知道过滤器何时更改并且应该重做v-for。我尝试过一种方法,但似乎也无法使它起作用。

How to filter data from a parent component in a child component?似乎与我想做的事情差不多,但是如果没有可靠的示例说明如何使它工作,我看不到如何将其组合在一起。

子组件:

export default {
  name: "mechanisms",
  props: ['games'],
  data() {
    return {
      inactiveMechanisms: []
    }
  },
  methods: {
    toggleActive(mechanism) {
      const idx = this.inactiveMechanisms.indexOf(mechanism);
      idx !== -1 ? this.inactiveMechanisms.splice(idx, 1) : this.inactiveMechanisms.push(mechanism);
      this.emitFilterClick();
    },
    emitFilterClick() {
      EventBus.$emit('mechanism-filter-change', this.inactiveMechanisms);
    }
  },
  computed: {
    allMechanisms() {
      const mechanisms = this.games.reduce((acc, game) => {
        game.mechanics.forEach((mechanism) => {
          acc.push(mechanism);
        });
        return acc;
      }, [])
      const uniqeMechanisms = Array.from(new Set(mechanisms).values()).sort();
      this.inactiveMechanisms = [];
      return uniqeMechanisms;
    }
  },
}
</script>

父母:

<mechanisms-filter v-bind:games="sortedGames" />
<div class="games" 
    v-bind:key=game.bggId v-for="game in filteredGames">
</div>

computed: {
    sortedGames() {
      return showBestAtFirst(this.userNames.length, [...this.games].sort(compareGameNames));
    },
    filteredGames() {
      return this.sortedGames;
    },
    showFilters() {
      return this.inactiveMechanisms;
    }
  }

我不知道应该如何过滤filterGames的结构/方式,以便在触发“ mechanism-filter-change”事件时更新它。使它成为计算的道具比方法更有意义,但是我不知道如何告诉计算的道具inactiveMechanisms发生了变化。

谢谢

0 个答案:

没有答案
相关问题