【问题标题】:how can i access a filtered array computed value in Vue.js?如何在 Vue.js 中访问过滤后的数组计算值?
【发布时间】:2020-11-17 06:49:43
【问题描述】:

我正在尝试访问我的模板中的过滤产品数组,但它当前返回为空。我在模板中将其称为{{product}}。我通过记录它们仔细检查了params 和名称匹配,它们匹配。我正在使用VueX 来存储数组并在组件中检索它。我尝试用mounted() 替换computed() 无济于事。

import axios from "axios";
import store from "../store/index.js";

export default {
  components: {
  },
  store,

  data: () => ({
    products: store.state.products
  }),
  computed: {
    product: function() {
      return this.products.filter(item => {
        item.name === this.$route.params.product;
      });
    }
  },

商店

export default new Vuex.Store({
  state: {
    products: [
      {
        name: "Basic Deck",
        price: 7,
        description:
          "The Basic Deck includes 68 cards: 10 cards in each of six categories, three icon legend cards, five blank cards for developing your own backstory elements, and instructions.",
        image: require("@/assets/Draeorc.png"),
      },
      {
        name: "Card Bundle",
        price: 10,
        description:
          "The Card Bundle includes the Basic Deck, Technical Booster, Mystical Booster and instructions as a single self-printable PDF.",
        image: require("@/assets/Twilight.png"),
      },
      {
        name: "Full Bundle with Box",
        price: 12,
        description:
          "The Full Bundle includes the Basic Deck, Technical Booster, Mystical Booster, instructions and tuck box as a single self-printable PDF.",
        image: require("@/assets/Orig_Godbringer.png"),
      }
    ],
  },
});

路由器

  {
    path: "/buy/:product",
    name: "Buy",
    component: () => import( "../views/Buy.vue"),
    props: true,
  },

【问题讨论】:

  • products数组的内容是什么?而且,你从 console.log(this.$route.params.product) 得到什么价值?
  • 它是一个对象数组。如果我退出 console.log(item.name + " " + this.$route.params.product);我得到 Card Bundle Card Bundle 所以他们匹配
  • 您能否同时发布数组和路由的内容,以便我们重现该问题?
  • 当然!它的更新

标签: vue.js vuejs2 vue-component vuex vue-router


【解决方案1】:

在过滤器回调中,您缺少返回条件return item.name === this.$route.params.product;,因此您应该这样做:

  computed: {
    product: function() {
      return this.products.filter(item => {
       return item.name === this.$route.params.product;
      });
    }
  },

  computed: {
    product: function() {
      return this.products.filter(item => item.name === this.$route.params.product);
    }
  },

【讨论】:

  • 谢谢!我忘了在 ES6 中为了避免写返回代码需要在一行上......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 2017-08-09
  • 2021-06-28
  • 2019-02-22
  • 2021-12-27
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多