Reputation: 13
I would like to push the input to the array. When I press the button to add the items nothing happens. I've searched multiple websites but it seems that I am too dumb to find the right code :( Do anyone know whats the problem with the code:
<!DOCTYPE html>
<head>
<title>Clientseitige Webentwicklung mit Vue.js</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app_basic">
<ul>
<li v-for="value in cars">{{ value }}</li>
</ul>
<input id="input1" type="text" v-model="newFarbe" placeholder="farbe">
<input id="input2" type="text" v-model="newMarke" placeholder="marke">
<input id="input3" type="text" v-model="newPS" placeholder="ps">
<button v-on:click="addCar">Hinzufügen</button>
</div>
<script>
var app_basic= new Vue(
{
el: '#app_basic',
data: {
cars:{
farbe: 'Blau',
marke: 'Ford',
ps: '240'
}
},
methods:{
addCar: function() {
this.cars.push({farbe : this.newFarbe, marke : this.newMarke, ps : this.newPS});
this.newFarbe='';
this.newMarke='';
this.newPS='';
}
}
});
</script>
</body>
</html>
Upvotes: 1
Views: 315
Reputation: 28404
cars
should be an array
and the inputs models should be defined in data
. Moreover, it's better to have some sort of validation before the insertion:
new Vue({
el: '#app_basic',
data: {
cars: [
{
farbe: 'Blau',
marke: 'Ford',
ps: '240'
}
],
newFarbe: '',
newMarke: '',
newPS: ''
},
methods:{
addCar: function() {
if(!this.newFarbe || !this.newMarke || this.newPS) return;
this.cars.push({
farbe : this.newFarbe, marke : this.newMarke, ps : this.newPS
});
this.newFarbe='';
this.newMarke='';
this.newPS='';
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app_basic">
<ul>
<li v-for="value in cars">
{{ value.farbe }} -
{{ value.marke }} -
{{ value.ps }}
</li>
</ul>
<input id="input1" type="text" v-model="newFarbe" placeholder="farbe">
<input id="input2" type="text" v-model="newMarke" placeholder="marke">
<input id="input3" type="text" v-model="newPS" placeholder="ps">
<button v-on:click="addCar">Hinzufügen</button>
</div>
Upvotes: 3