How can I change the style of the number in stock when 0, 0 needs to be in red? So basically I have a displayed number in stock that increments and decrements if you add an item to a cart. But if number in stock is 0, I need 0 to be red color. How can I do it?
HTML:
<div id="app">
<div >
<p>Cart({{ cart }})</p>
</div>
<product @add-to-cart="updateCart" @remove-from-cart="removeItem"></product>
</div>
VUE.js:
Vue.component('product', {
template:
`
<div >
<div >
<img :src="image" />
</div>
<div >
<h1>{{ product }}</h1>
<p v-if= "inStock > 0"> In Stock: {{inStock}}</p>
<p v-else>No more in stock {{inStock}}</p>
<button @click="addToCart"
:disabled="!inStock"
:> </button>
<button @click="removeFromCart"
:disabled="inStock==10"> - </button>
</div>
</div>
`,
data() {
return {
product: 'Hoodie',
image: 'hoodie.jpeg',
inStock: 10,
cart: 0
}
},
methods: {
addToCart: function() {
this.$emit('add-to-cart'),
this.inStock -= 1
},
removeFromCart: function() {
this.$emit('remove-from-cart'),
this.inStock = 1
}
}
})
var app = new Vue({
el: '#app',
data: {
cart: 0
},
methods: {
updateCart() {
this.cart = 1
},
removeItem() {
this.cart -= 1
}
}
})
CodePudding user response:
You can set a class
on an element dynamically, using :class
with an object.
For example:
<p:>{{ inStock }}</p>
This will apply the class isRed
on this p
if inStock
is 0.
You then just need to define the appropriate css
for isRed
:
.isRed {
color: red;
}
CodePudding user response:
You can use style
and span
:
Vue.component('product', {
template:
`
<div >
<div >
<img :src="image" />
</div>
<div >
<h1>{{ product }}</h1>
<p v-if="inStock > 0"> In Stock: {{inStock}}</p>
<p v-else>No more in stock <span style="color: red;">{{inStock}}</span></p>
<button @click="addToCart"
:disabled="!inStock"
:> - </button>
<button @click="removeFromCart"
:disabled="inStock==10"> </button>
</div>
</div>`,
data() {
return {
product: 'Hoodie',
image: 'hoodie.jpeg',
inStock: 10,
cart: 0
}
},
methods: {
addToCart: function() {
this.$emit('add-to-cart'),
this.inStock -= 1
},
removeFromCart: function() {
this.$emit('remove-from-cart'),
this.inStock = 1
}
}
})
var app = new Vue({
el: '#app',
data: {
cart: 0
},
methods: {
updateCart() {
this.cart = 1
},
removeItem() {
this.cart -= 1
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div >
<p>Cart({{ cart }})</p>
</div>
<product @add-to-cart="updateCart" @remove-from-cart="removeItem"></product>
</div>