Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tillklockmann/c2f5e6f056dbf92af36ca69cb4f424f6 to your computer and use it in GitHub Desktop.
Save tillklockmann/c2f5e6f056dbf92af36ca69cb4f424f6 to your computer and use it in GitHub Desktop.
Vue Components comunicating with the parent
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>{{title}}</h1>
<select v-model="selected">
<option>my-comp</option>
<option>my-other-comp</option>
</select>
<my-comp v-if="selected == 'my-comp'" @from-comp="onFromComp" comp-title="My Comp"></my-comp>
<my-other-comp v-if="selected == 'my-other-comp'" @from-comp="onFromComp" comp-title="My Other Comp"></my-other-comp>
</div>
<script>
Vue.component('my-comp', {
// camelCase in JavaScript
props: ['compTitle'],
template:
`
<div>
<h3>{{ compTitle }}</h3>
<button @click="$emit('from-comp', mssg)">back to parent</button>
</div>
`,
data: function(){
return {
mssg: 'from comp'
}
}
})
Vue.component('my-other-comp', {
// camelCase in JavaScript
props: ['compTitle'],
template:
`
<div>
<h3>{{ compTitle }}</h3>
<input v-model="data['mssg']">
<input v-model="data['mssg1']">
<button @click="$emit('from-comp', data)">back to parent</button>
<code>{{data}}</code>
</div>
`,
data: function(){
return {
data: {
mssg : 'from the first input',
mssg1 : 'from the second input',
}
}
}
})
new Vue({
el: '#app',
data: {
title: 'My Vue Test Project',
selected: 'my-comp',
},
methods: {
onFromComp: function(data) {
console.log(data)
}
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment