Нет информации, передаваемой в модальное окно из списка товаров: Ошибка в v-on обработчике: «Ошибка типа: _vm.selectProduct не является функцией» - PullRequest
0 голосов
/ 14 октября 2019

У меня есть список товаров, в котором есть кнопка «Подробнее», которая откроет модальное окно, содержащее информацию о конкретном товаре. Я использовал $ emit для передачи информации со страницы моего продукта в модальное окно. Я вижу открытое модальное окно, но не вижу информации о конкретном продукте, определенной в Modal_window.vue.

Я получаю сообщение об ошибке:

[Vue warn]: Error in v-on handler: "TypeError: _vm.selectProduct is not a function"

vue.esm.js?efeb:1897 TypeError: _vm.selectProduct is not a function

Это мой код:

Product_listing.vue

<template>
  <div class="content">
    <div v-for="product in productsWithHeadlines" :key="product.id">
      <div class="one">
        <span>{{product.name}}</span>
      </div>
      ...
      <div class="seven">
        <b-btn class="more_details_button" @click="selectProduct(product)">More details</b-btn>
      </div>

    </div>
  </div>
</template>

<script>

export default {
  component: {
    modal_window: Modal_window
  },

  data() {
    return {
      showModal: false,
      selectedProduct: undefined,

      products: [
        {
          ID: "1",
          Name: "Product_1",
          Headline_1: "Headline 1",
          top_feature_1:
            "This is the description of the feature of product 1 under the first headline",
          Headline_2: "Headline 2",
          top_feature_2:
            "This is the description of the feature of product 1 under the second headline",
          Headline_3: "Headline 3",
          top_feature_3:
            "This is the description of the feature of product 1 under the third headline",
        },
{
          ID: "2",
          Name: "Product_2",
          Headline_1: "Headline 1",
          top_feature_1:
            "This is the description of the feature of product 2 under the first headline",
          Headline_2: "Headline 2",
          top_feature_2:
            "This is the description of the feature of product 2 under the second headline",
          Headline_3: "Headline 3",
          top_feature_3:
            "This is the description of the feature of product 2 under the third headline",
        }
      ]
    };
  },
  computed: {
    selectProduct(product) {
      this.selectedProduct = product;
      this.$emit("openModalWindow", this.selectedProduct);
    },

    productsWithHeadlines() {
      return this.products.map(product => {
        const totalKeys = Object.keys(product).length;
        const headlines = [];
        for (let index = 1; index < totalKeys; index += 1) {
          const text = product[`Headline_${index}`];
          const feature = product[`top_feature_${index}`];
          if (text && feature) headlines.push({ text, feature });
        }

        return {
          id: product.id,
          name: product.Name,
          headlines,
        };
      });
    }
  }
};
</script>

Modal_window.vue Я использую элемент данных заголовков в модальном окне вместе с именем.

<template id="modal-template">
  <b-modal id="showModal" :hide-footer="true" ok-title="Buy Now" size="lg" :title="product.name">
    <div class="inner-container">
      <div class="inner-nested">
        <div class="inner-one">
          {{ product.name }}
       </div>
          <ul>
            <li v-for="(headline, index) in product.headlines" :key="index">
              <div>{{ headline.text }}</div>
              <div>{{ headline.feature }}</div>
            </li>
          </ul>
          <br />
          <br />
        </div>

      </div>
    </div>
  </b-modal>
</template>

<script>

export default {
  data() {
    return {
      showModal: false,
      product: { type: Object, default: null }
    };
  },
  methods: {
    openModal(newProduct) {
      console.log(newProduct);
      this.product = newProduct;
      this.$bvModal.show("showModal");
    }
  }
};
</script>

Буду признателен за помощь, спасибо!

1 Ответ

1 голос
/ 14 октября 2019

Как указано в сообщении об ошибке - selectProduct не является функцией, которая сама решает проблему здесь.

Понимает, как вычисляется и свойство методов vue отличается.

Вычислено Эти свойства преобразуются как свойство vue с помощью методов получения и установки, что означает, что вы можете либо получить значение из него, либо установить предопределенное значение. Он не принимает параметр дляэто

Ex -

computed : {
  hello() {
    return 'helloWorld' // Getting a value 
  }
}

вы будете использовать его как this.hello, где в качестве методов, которые являются точной копией обычного function в JS, где со способностями понимания других vueсвойство

methods : {
      hello(name) {
        return 'hello' + name // Getting a value 
      }
    }

Как уже говорилось, это fn, поэтому он также может иметь параметр, и вы можете использовать его как fn как this.hello(name)

В вашем случае вы, вероятно, захотитепереместите ваше свойство selectProduct в свойство methods вместо свойства computed.

...