如果有过滤器

时间:2018-04-04 18:24:25

标签: vue.js vuejs2 vue-filter

有没有办法在VueJS中执行此过滤规则?

  

如果某个元素包含过滤器discount,则父级将收到类color-green(在本例中为标记范围)

I made a JSFIDDLE :)

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

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

.color-green{
  color: green;
}

1 个答案:

答案 0 :(得分:1)

但在你的情况下,每个元素都有折扣不是吗?

过滤器不是您要检查的内容。过滤只是将某些输入转换为某种输出的一种方法。

应在产品数据中定义折扣信息。然后你可以做这样的事情:

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>