Reputation: 320
I want to insert a component inside another one.
I dont know what I´m doing wrong, but the example does not work.
Here is my Vue instance and component definition:
new Vue({
el:"#show",
components:{
dinnerMenu
},
data:{
work:true
}
});
Vue.component("dinnerMenu", {
template: `
<ul>
<li v-for="item in food">{{food}}</li>
</ul>
`,
data() {
return {
food: ['eggs', 'milk']
}
}
});
new Vue({
el: "#secondLayer"
});
And here the html code:
<div id="show">
<template v-if="work">
<div id="secondLayer">
<dinnerMenu></dinnerMenu>
</div>
</template>
</div>
Here is the code in js fiddle so you can give it a try by yourself.
Upvotes: 1
Views: 560
Reputation: 1918
I see three basic problems in the code. First, you can check your console it already says what the problem is.
You use
components: {
dinnerMenu
}
Which is the short version of
components: {
dinnerMenu: dinnerMenu // Key dinnerMenu and value is value of "dinnerMenu" variable.
}
But you do not have a dinnerMenu variable. First initialize it. You need to reformat your code like below:
dinnerMenu = Vue.component("dinnerMenu", {
template: `
<ul>
<li v-for="item in food">{{food}}</li>
</ul>
`,
data() {
return {
food: ['eggs', 'milk']
}
}
});
new Vue({
el:"#show",
components:{
dinnerMenu
},
data:{
work:true
}
});
new Vue({
el: "#secondLayer"
});
Second problem is not visible in your post here but it is visible in js fiddle. It is related with vue binding on incorrect HTML element.
Your HTML structure is this:
<div id="show">
<template v-if="work">
<div id="secondLayer">
<dinnerMenu></dinnerMenu>
</div>
</template>
</div>
Notice, id of div is "secondLayer" but you register your custom component to a different Vue instance. el:"#show"
You should register it for correct Vue instance.
new Vue({
el:"#show",
/* REMOVED components:{
dinnerMenu
}, */
data:{
work:true
}
});
new Vue({
el: "#secondLayer",
components:{
dinnerMenu
}, // ADDED
});
The last problem is your component call in HTML. You should use kebab case.
<div id="show">
<template v-if="work">
<div id="secondLayer">
<dinner-menu></dinner-menu> <!-- Use kebab case for your custom components -->
</div>
</template>
</div>
That should work.
In addition, please try to write clear code for "future you" and other people. Follow best practices and some styling rules.
Also please add your HTML to the your question so other's can see and understand the problem better.
If you don't want to follow kebab-case-custom-component convention, please read about component registration from VueJS official docs.
Upvotes: 2