Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save balazimichal/d37eed34ad30711171ae3f66ad6a9ed5 to your computer and use it in GitHub Desktop.
Save balazimichal/d37eed34ad30711171ae3f66ad6a9ed5 to your computer and use it in GitHub Desktop.
vue-car-counter
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Vue</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>Car Counter</h1>
<input type="text" v-on:keydown.enter="addCar" />
<ul>
<li v-for="car in cars">{{ car.color }} - ({{ car.count }}) <button v-on:click="increaseCount(car.id)">+</button><button v-on:click="decreaseCount(car.id)">-</button><button v-on:click="removeCar(car.id)">remove</button></li>
</ul>
{{ vueState() }}
</div>
<script>
new Vue({
el: '#app',
data: {
value: '',
cars : [
{id: 1, color: 'red', count: 0},
{id: 2, color: 'green', count: 0},
{id: 3, color: 'blue', count: 0}
]
},
methods: {
addCar : function(event) {
this.value = event.target.value
const newCar = {id: this.randID(), color: this.value, count: 0}
this.cars = [...this.cars, newCar]
event.target.value = ''
},
removeCar : function(carID) {
this.cars = this.cars.filter(function(car){
return car.id != carID
})
},
increaseCount : function(carID) {
this.cars = this.cars.map(function(car) {
if(car.id == carID) {
car.count == car.count ++
return car
} else {
return car
}
})
},
decreaseCount: function (carID) {
this.cars = this.cars.map(function (car) {
if (car.id == carID) {
car.count == car.count--
return car
} else {
return car
}
})
},
vueState : function() {
return JSON.stringify(this.cars)
},
randID : function() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment