Vue - Snippets
Basics
- Data Option / Function
- Methods Option / Object
- Outputting Data mit
- Interpolation {{}}
- Bindings v-bind:property="myVal"
- Methods
- JavaScript Objects
- this
// create App
const app = Vue.createApp();
// mount a html region
// app.mount('cssSelector');
app.mount('#myId'); // Vue controls now this id in the DOM
const app = Vue.createApp({
// DATA FUNCTION can hold key val pairs
data() { //or data: function(){...}
return{ // data always returns an object
myVar: 'Learn Vue',// can store keys with vals of every type(bool, object, string...)
myVar2: 'Master Vue<,
myHTML: '<h3>HTML Code</h3>', // use v-html to output html code
myLink: 'https://viewjs.org'
};
}
// METHODS OBJECT HOLDS FUNCTIONS
methods: {
outputGoal(){
const randomNumber = Math.random();
if (randomNumber < 0.5) {return 'Learn Vue';}
else {return this.myVar2} // 'this' works because vue merges all data and methods in a global vue object
}
}
});
<div id="myId">
<h3>Interpolation</h3>
<p>{{ myVar }}</p> <!-- Interpolation outputs "Learn Vue" -->
<h3>Binding</h3>
<p>Use bindings to set attributes. I.e. set the href attribute. {{myLink}} wouldn't work inside of tags.</p>
<p>Learn more <a v-bind:href="myLink">about Vue</a></p>
<p>{{ outputGoal() }}</p><!-- functions or simple js expresseions like 1+1 work to -->
<p v-html="myHTML"></p>
</div>
Events
v-on
Beispiel
const app = Vue.createApp({
data() {
return {
counter: 0,
};
},
methods:{
plus(n){ this.counter = this.counter + n },
minus(n){ this.counter = this.counter - n },
updateName(event){
this.name = event.target.value
}
}
});
app.mount('#events');
<section id="events">
<h2>Events in Action</h2>
<p> We can use expression in v-on:click or use a function from our methods object</p>
<!-- CLICK EVENT -->
<button v-on:click="plus(5)">Add 5</button>
<button v-on:click="minus(5)">Substract 5</button>
<p>Result: {{ counter }}</p>
<!-- INPUT EVENT -->
<input type="text" v-on:input="updateName">
<p>Hello {{ name }}</p>
</section>
$event
In Eventlistenern kann man automatisch auf das event Argument zugreifen, das der Browser automatisch mitliefert (siehe Beispiel oben). Wenn man allerdings selbst ein Argument übermittelt wird das Event Argument überschrieben. Man kann aber mit dem reservierten Argument $event trotzdem wieder auf das Event Objekt zugreifen:
updateName(event, lastName){
this.name = event.target.value + ' ' + lastName
}
<input type="text" v-on:input="updateName($event,'Schlegel')">
<p>Hello {{ name }}</p>
Event Modifiers
Es gibt verschiedene Event Modifier z.B. um sich ein event.preventDefault() zu sparen. Event Modifiers werden mit einem '.' an das Event im HTML angehängt
v-on:submit.prevent
https://vuejs.org/v2/guide/events.html#Event-Modifiers
Click Modifiers
v-on:click.right v-on:click.middle ...
Key Modifiers
//.enter means fire only if ENTER Key is pressed v-on:keyup.enter="confirmInput" //possible is all ctrl, shift, page-down...
<!--also multiple v-on handlers are possible-->
<input type="text"
v-on:input="updateName"
v-on:keyup.enter="confirmName">
<p>Hello {{ confirmedName }}</p>
const app = Vue.createApp({
data() {
return {
name: '',
confirmedName: '',
};
},
methods:{
updateName(event, lastName){
this.name = event.target.value
},
confirmName(){
this.confirmedName = this.name
}
}
});
app.mount('#events');
Two way binding
Bei Input Feldern möchten wir oft einerseits
1. Eine data Property mit mit der User Eingabe setzen 2. Eine data Property auslesen und im value Attribut setzen.
Das bedeutet wir müssen das Input Feld auf zwei Wegen verbinden
Beispiel Reset Button
Das Input Feld bekommt 2 Binds
1. Value Attribut wird an das "name" Property gebuden. 2. Input Event wird an die Funktion "setName" gebunden.
Wird von irgendwoher (in unserem Fall vom Reset Knopf) die Eigenschaft "name" verändert, so wird auch der value im Input automatisch verändert. In Vanilla JS müßten wir alle Stellen in denen name gesetzt ist von Hand zurücksetzen müssen.
<input type="text" v-bind:value="name" v-on:input="setName($event)">
<p>Your Name: {{ name }}</p>
<button v-on:click="reset()">Reset</button>
//...
data() {
return { name: '' };
},
methods: {
setName(event) { this.name = event.target.value; },
reset() { this.name = ''; }
}
//...
v-model two-way-binding
Die Kombination aus Eventhandling (Ereignisbehandlung = Aufrufen einer Funktion bei einem Event) und Databinding (Die Bindung des Wertes an eine Eigenschaft) gibt es sehr oft. Daher gibt es für dieses Muster eine eigene Direktive.
Statt Da das two-way-binding auf Input-Feldern häufig vorkommt bietet Vue einen Shortcut dafür an.
<input type="text" v-bind:value="name" v-on:input="setName($event)">
schreiben wir nur
<input type="text" v-model="name">
Die Funktion setName die wir oben haben entfällt komplett. Denn die Eigenschaft "name" kann mit two-way-binding getter als auch setter sein also gesetzt werden und auch setzen.
Computed Properties
Wir können Interpolations auch mit Funktionen nutzen:
Vorlage:MyFunction()
Das kann allerdings in Performance Problemen enden. Da Vue nicht weiß welche Properties in der Funktion angepasst werden führt es diese Funktion bei jeder Änderung von irgendwelchen Properties in data aus, auch wenn das gar nicht notwendig ist. Um das zu umgehen gibt es die Computed Properties.