【问题标题】:Vue 2 Mixin doesn't work properly in v-for "[Vue warn]: Error in render: "TypeError: Cannot read property 'discountCalc' of undefined""Vue 2 Mixin 在 v-for “[Vue warn]: Error in render: “TypeError: Cannot read property 'discountCalc' of undefined”中无法正常工作“”
【发布时间】:2021-09-11 13:17:31
【问题描述】:

#laravel-8 + vue 2

我做了一个这样的混合:mixins/globalMixin.js:

import Vue from "vue";
Vue.mixin({
    methods: {
        price(item, pricePeriod) {
            return pricePeriod == "monthly"
                ? ((pricePeriod = "monthly"),
                  this.financial(this.priceRates(item["price_m"])))
                : ((pricePeriod = "yearly"),
                  this.financial(this.priceRates(item["price_y"] / 12)));
        },
        priceRates(price, localCurrency) {
            return localCurrency == "EUR"
                ? price / 10.5
                : localCurrency == "USD"
                ? price / 8.9
                : price;
        },
        discountCalc(price, itemCoupon, pricePeriod) {
            return itemCoupon && pricePeriod == "yearly"
                ? this.financial(price - (price * itemCoupon.percentage) / 100)
                : this.financial(price);
        },
        financial(x) {
            return Number.parseFloat(x).toFixed(2);
        }
    }
});

然后我将它导入 app.js 导入“./mixins/globalMixin.js”;

到现在还好

在像这样的 vue 模板中使用它可以正常工作

<b>{{
    this.discountCalc(
        this.price(item, pricing.period),
        item.coupon,
        localCurrency.name
    )
}} </b>

但是当我像这样在 v-for 中使用它时会出现问题:

<ul class="list-unstyled mb-3 position-relative">
<li
    v-for="(subItem, index) in JSON.parse(
        item.info
    )"
    :key="index"
>
{{
    this.discountCalc(
        this.price(item, pricing.period),
        item.coupon,
        localCurrency.name
    )
}} 
</li>
</ul>

控制台错误: [Vue警告]:渲染错误:“TypeError:无法读取未定义的属性'discountCalc'”

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component laravel-8


    【解决方案1】:

    您应该从模板中删除this

    <ul class="list-unstyled mb-3 position-relative">
                <li v-for="(subItem, index) in JSON.parse(item.info)" :key="index">
                  {{
                   discountCalc(
                      price(item, pricing.period),
                      item.coupon,
                      localCurrency.name
                    )
                  }}
                </li>
              </ul>
    

    【讨论】:

      猜你喜欢
      • 2017-12-29
      • 2017-04-24
      • 2023-03-31
      • 2023-01-19
      • 2017-09-23
      • 2021-09-18
      • 2017-02-18
      • 2019-02-12
      • 2017-12-29
      相关资源
      最近更新 更多