Skip to content

Instantly share code, notes, and snippets.

@damir-bubanovic
Last active March 6, 2017 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damir-bubanovic/31ef488aecbc703d52adc2d5280aa87c to your computer and use it in GitHub Desktop.
Save damir-bubanovic/31ef488aecbc703d52adc2d5280aa87c to your computer and use it in GitHub Desktop.
Vue.js 2.0 - using $emit to pass data
/**
* ULTRA Dynamic $emit [pass data from sister to parent to brother - to populate list]
*
LINKS:
1) Advanced technique - have not tried
https://vuejs.org/v2/guide/migration.html#dispatch-and-broadcast-replaced
2) Similar
http://stackoverflow.com/questions/40835293/vue-laravel-access-and-use-eventhub
*
* EXTRA ARRAY (pass multiple input values)
https://jsfiddle.net/a5t24gm3/1/
*
* EXTRA OBJECT (pass multiple input values as object)
*/
/**
* SISTER
*/
<template>
<div>
/*EXTRA ARRAY & OBJECT*/
<input v-model="newname.first"><br>
<input v-model="newname.last"><br>
<button v-on:click="sendname">Send Name</button>
/*ULTRA*/
<input v-model="newname"><br>
<button v-on:click="sendname">Send Name</button>
</div>
</template>
<script>
export default {
data() {
return {
/*EXTRA ARRAY*/
newname: []
/*EXTRA OBJECT*/
newname: { first: '', last: '' }
/*ULTRA*/
newname: ''
}
},
methods: {
sendname() {
/*EXTRA & ULTRA*/
this.$emit('sister', this.newname)
}
}
}
</script>
/**
* PARENT
*/
<p>Parent component</p><br>
<hr>
<p>Brother component</p><br>
<brother v-for="name in names" v-bind:name="name"></brother>
<hr>
<p>Sister component</p><br>
<sister v-on:sister="storeData"></sister>
Vue.component('brother', require('./components/Brother.vue'));
Vue.component('sister', require('./components/Sister.vue'));
const app = new Vue({
el: '#app',
data: {
/*EXTRA*/
names: [
{ first: 'Gina', last: 'Capwell' },
{ first: 'Viki', last: 'Small' },
{ first: 'O.G', last: 'Shorty' }
]
/*ULTRA*/
names: [
'Vlatka',
'Gina',
'Ivana'
]
},
methods: {
storeData(name) {
this.names.push(name)
// console.log('New Name is:', name)
}
}
});
/**
* BROTHER
*/
<template>
<div>
/*EXTRA*/
<p>{{ name.first }} {{ name.last }}</p>
/*ULTRA*/
{{ name }}
</div>
</template>
<script>
export default {
props: ['name']
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment