Vue.js - Computed Properties and Watcher
Understanding computed Computed properties and Watchers
by Alligatorio
HTML
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<div v-for="subject in results">
<input v-model="subject.marks">
<span>Marks for {{ subject.title }}: {{ subject.marks }}</span>
</div>
<span>Total marks are: {{ totalMarks }}</span>
<hr>
<input v-model="tempName">
<button v-on:click="setName()">set</button><br>
<span>{{ fullName }}</span><br>
<span>first name: {{ firstName }}</span><br>
<span>last name: {{ lastName }}</span>
</div>
JavaScript
var app = new Vue({
el: '#app',
data() {
return {
tempName: '',
firstName: '',
lastName: '',
results: [
{
name: 'English',
marks: 70
},
{
name: 'Maths',
marks: 80
},
{
name: 'History',
marks: 90
}
]
}
},
computed: {
totalMarks: function () {
let total = 0;
for (let i = 0; i < this.results.length; i++){
total += parseInt(this.results[i].marks);
}
return total;
},
fullName: {
get: function() {
return this.firstName + ' ' + this.lastName;
},
set: function(value) {
let names = value.split(' ');
this.firstName = names[0];
this.lastName = names[names.length - 1];
}
}
},
methods: {
setName: function() {
this.fullName = this.tempName;
}
}
})