Vue 2 Mixin 在 v-for “[Vue warn]: Error in render: “TypeError: Cannot read property 'discountCalc' of
Posted
技术标签:
【中文标题】Vue 2 Mixin 在 v-for “[Vue warn]: Error in render: “TypeError: Cannot read property \'discountCalc\' of undefined”中无法正常工作“”【英文标题】: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'”
【问题讨论】:
【参考方案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>
【讨论】:
以上是关于Vue 2 Mixin 在 v-for “[Vue warn]: Error in render: “TypeError: Cannot read property 'discountCalc' of的主要内容,如果未能解决你的问题,请参考以下文章