1π
β
What you looking for is called concatenation
add an +
infront of =
Example:
this.sentence = "Q"
to this.sentence += "Q"
Thats the same as if you would write: this.sentence = this.sentence + "Q"
its just a shortcut
var app = new Vue ({
el: '#app',
data : {
sentence: ''
},
methods: {
Q: function () {
this.sentence += "Q"
},
W: function () {
this.sentence += "W"
},
E: function () {
this.sentence += "E"
},
R: function () {
this.sentence += "R"
},
T: function () {
this.sentence += "T"
},
Y: function () {
this.sentence += "Y"
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button @click="Q">Q</button>
<button @click="W">W</button>
<button @click="E">E</button>
<button @click="R">R</button>
<button @click="T">T</button>
<button @click="Y">Y</button>
</div>
π€bill.gates
2π
You can easily concat the string from your template @click event like so :
Method 1
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button @click="sentence += 'Q'">Q</button>
<button @click="sentence += 'W'">W</button>
<button @click="sentence += 'E'">E</button>
<button @click="sentence += 'R'">R</button>
<button @click="sentence += 'T'">T</button>
<button @click="sentence += 'Y'">Y</button>
</div>
Method 2
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button @click="addToSentence('Q')">Q</button>
<button @click="addToSentence('W')">W</button>
<button @click="addToSentence('E')">E</button>
<button @click="addToSentence('R')">R</button>
<button @click="addToSentence('T')">T</button>
<button @click="addToSentence('Y')">Y</button>
</div>
with a dedicated method
data() {
return {
sentence: ''
}
},
methods: {
addToSentence(letter) {
this.sentence += letter
}
}
Method 3
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button v-for="letter in ['Q','W','E','R','T','Y']" @click="addToSentence(letter)">{{ letter }}</button>
</div>
with a dedicated method
data() {
return {
sentence: ''
}
},
methods: {
addToSentence(letter) {
this.sentence += letter
}
}
Method 4
More compact
<div id="app">
<p>Sentence : {{ sentence }}</p>
<button v-for="letter in ['Q','W','E','R','T','Y']" @click="sentence += letter">{{ letter }}</button>
</div>
data() {
return {
sentence: ''
}
},
π€LouLav
Source:stackexchange.com