Use methods and computed properties in child component

萝らか妹 提交于 2020-08-10 20:20:28

问题


In my List component I have a method which count the length of the array within certain categories.

methods: {
    getLengthofaCategory(cat) {
      const LowerCaseSearch = this.search.toLowerCase();
      let categoryCount = this.products.filter(
        product =>
          (product.name.toLowerCase().includes(LowerCaseSearch) ||
            product.category.toLowerCase().includes(LowerCaseSearch)) &&
          (!this.checked.length || this.checked.includes(product.category)) &&
          product.category === cat
      );

      return categoryCount.length;
    }
  }

See here my setup in this sandbox.

But I want the values next to the checkboxes (which are coming from my CheckBox component).

How do I get the logic from the method getLengthofaCategory into my CheckBox component?

So I am able to use {{ getLengthofaCategory('tennis') }} in the v-for loop, inside the CheckBox component. And then maybe I can also use category.value instead of hardcoding e.g 'tennis' as the paramater?


回答1:


In your list.vue, you can use the already created computed function filteredData instead of doing the filter again. This saves some performance because in Vue, computed properties are "cached" once run.

So you can create a new computed function that creates an object with keys per category and value can either be just the amount or an array of products in this category.

I would then pass this computed value to the CheckBox component via a prop, then inside the CheckBox component, you can display the .length or value regarding how many items each category has:

List.vue:

    computed: {
    //...
      amountPerCategory() {
        return this.filteredData.reduce((categories, product) => {
          if (!(product.category in categories)) {
            categories[product.category] = [];
          }

          categories[product.category].push(product);

          return categories;
        }, {});
      }
    }

CheckBox.vue:

        <span class="ml-2 text-gray-700 capitalize">{{ category.value }}</span> -
        <span
          v-if="count[category.value]"
          class="ml-2 text-gray-700 capitalize"
        >{{ count[category.value].length }}</span>
 count: {
   type: Object,
   default: () => ({})
 }

https://codesandbox.io/s/admiring-ellis-4hojl?file=/src/components/CheckBox.vue



来源:https://stackoverflow.com/questions/62612991/use-methods-and-computed-properties-in-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!