Sync in Vue 2.x
by asemahle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.js"></script>
<div id="app">
<p>
Value in parent: {{title}}
</p>
<custom-component :value_sync="title" v-on:value-change="title = arguments[0]"></custom-component>
<button v-on:click="title = 'Changed From Parent!'">CHANGE FROM PARENT</button>
</div>
<template id="custom-component">
<div>
<p>
Value in child: {{value}}
</p>
<button v-on:click="value = 'Changed From Child!'">CHANGE FROM CHILD</button>
</div>
</template>
JavaScript
Vue.component('custom-component', {
template: '#custom-component',
props: ['value_sync'],
data: function() {
return {
value: '',
}
},
watch: {
'value_sync': function() {
this.value = this.value_sync;
},
'value': function() {
this.$emit('value-change', this.value);
}
},
created() {
this.value = this.value_sync;
}
});
var app = new Vue({
el: '#app',
data: {
title: 'Original Value',
}
});