[英]VueJS add class if has filter
Is there a way to do this filter rule in VueJS? 有没有办法在VueJS中执行此过滤规则?
If some element has the filter
discount
, the parent will receive the classcolor-green
(in this case the tag span) 如果某些元素具有滤镜discount
,则父级将收到color-green
的类(在这种情况下为标签范围)
I made a JSFIDDLE :) 我做了一个JSFIDDLE :)
HTML HTML
<div id="app">
<h3>50% Discount =)</h3>
<ul>
<li v-for="product in products">
{{ product.name }} - <span> {{ product.price | discount }} </span>
</li>
</ul>
</div>
JS JS
Vue.filter('discount', function (value) {
return value * 0.5;
})
new Vue({
el: '#app',
data: {
products: [
{name: 'Angular', price: 75},
{name: 'VueJS', price: 60},
{name: 'React', price: 40}
]
}
})
CSS CSS
.color-green{
color: green;
}
But in your case every element has a discount isn't it? 但是在您的情况下,每个元素都有折扣吗?
Filter is not something you want to check. 过滤器不是您要检查的东西。 Filter is just a way to transform some input to some output. 过滤器只是将某些输入转换为某些输出的一种方法。
Discount info should be defined inside your products data. 折扣信息应在您的产品数据中定义。 And then you can make something like this: 然后,您可以进行如下操作:
Vue.filter('discount', function (value) { return value * 0.5; }) new Vue({ el: '#app', data: { products: [ {name: 'Angular', price: 75, discount: 0.3}, {name: 'VueJS', price: 60}, {name: 'React', price: 40, discount: 0.7} ] } })
.color-green{ color: green; } .product-price--discounted { text-decoration: line-through; }
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> <div id="app"> <h3>Products</h3> <ul> <li v-for="product in products"> {{ product.name }} - <span :class="product.discount && 'product-price--discounted'">{{ product.price }}</span> <span v-if="product.discount" class="color-green"> {{ product.price - product.price * product.discount}} </span> </li> </ul> <h3>All elements has discount:</h3> <ul> <li v-for="product in products"> {{ product.name }} - <span class='color-green'>{{ product.price | discount }}</span> </li> </ul> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.