Trying to create a nested component in VueJS has been a bit challenging for me. I have attempted something like this, but unfortunately, it doesn't seem to work as expected (the child component does not display anything):
I am interested in exploring both inline-templates and the .vue file extension method for achieving this nested component structure.
Below is the code snippet from the example that didn't work:
main.js
import Vue from 'vue'
import App from './App.vue'
import Child from './Child.vue'
new Vue({
el: 'body',
components: { App, Child }
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<app></app>
<script src="main.js"></script>
</body>
</html>
App.vue
<template>
<div>
<h1>{{ parent_msg }}</h1>
<child></child>
</div>
</template>
<script>
export default {
data () {
return {
parent_msg: 'Hello From the Parent!'
}
}
}
</script>
Child.vue
<template>
<h1>{{ child_msg }}</h1>
</template>
<script>
export default {
data () {
return {
child_msg: 'Hello From the Child!'
}
}
}
</script>
While the example above is hosted on webpackbin.com, I am working on two projects using Laravel and Laravel Spark respectively. In the Laravel project, I primarily use .vue files, while in the Laravel Spark project, I rely more on inline-templates. Any functional samples or suggestions would be greatly appreciated. Thank you!
UPDATE
Credit to Linus for the helpful answer provided below. It seems that I need to make adjustments in my main.js file to register the child component globally:
import Vue from 'vue'
import App from './App.vue'
import Child from './Child.vue'
Vue.component('child', Child);
new Vue({
el: 'body',
components: { App, Child }
})
Alternatively, if I want to keep the child component local within the parent component only, I could modify the parent component (App.vue) like so:
<template>
<h1>{{ parent_msg }}</h1>
<div>
<child></child>
</div>
</template>
<script>
import Child from './Child.vue';
export default {
components: {Child},
data () {
return {
parent_msg: 'Hello from the parent component!'
}
}
}
</script>