Order of Operations for Event Based Prop Update Vue JS
by asemahle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.7/vue.js"></script>
<div id="app" v-cloak>
{{title}}
<custom-component
:val="title"
v-on:val-changed="setTitle"
v-on:val-changed.native="setTitle($event.detail)"
></custom-component>
</div>
<template id="custom-component">
<div>
<button v-on:click="changeByEmit">CHANGE BY EMIT!</button>
<button v-on:click="changeByDispatch">CHANGE BY DISPATCH!</button>
</div>
</template>
JavaScript
Vue.component('custom-component', {
template: '#custom-component',
props: {
val: String,
},
data: function() {
return {
times: 0
}
},
methods: {
changeByEmit: function() {
this.times++;
var newTitle = 'Times changed ' + this.times;
this.$emit('val-changed', newTitle);
console.log('COMP - The value is ', this.val);
},
changeByDispatch: function() {
this.times++;
var newTitle = 'Times changed ' + this.times;
var event = new CustomEvent('val-changed', { 'detail': newTitle });
this.$el.dispatchEvent(event);
console.log('COMP - The value is ', this.val);
}
}
});
var app = new Vue({
el: '#app',
data: {
title: 'Original Value',
},
methods: {
setTitle: function(title) {
console.log('BASE - The new title is ', title);
this.title = title;
}
}
})