I'm working with a very simple Vue 3 app, listed below.
Due to the nature of our project, we want use in-DOM templates.
This works fine for a single component. But once a child component is added, this component does not work.
See the example below, where SubComponent stops working when we enable the createApp for the App component.
I've tried using slots, experimented with registering as components, but none of these work.
What am I overlooking?
const {ref} = Vue;
const SubComponent = {
setup() {
const text = ref("");
return {
text
};
}
};
const App = {
setup() {
const count = ref(0);
const inc = () => {
count.value++;
};
return {
count,
inc
};
}
}
Vue.createApp(SubComponent).mount("#subcomponent");
Vue.createApp(App).mount('#app')
<head>
<script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
</head>
<body>
<div id="app">
<h1>Hello Vue 3!</h1>
<button @click="inc">Clicked {{ count }} times.</button>
<div id="subcomponent">
<h2>Hello from subcomponent</h2>
<input v-model="text" />
<br />
<span>{{text}}</span>
</div>
</div>
</body>
Maybe like following snippet:
const {ref} = Vue;
const SubComponent = {
template: `
<h2>Hello from subcomponent</h2>
<input v-model="text" />
<br />
<span>{{text}}</span>
`,
setup() {
const text = ref("");
return { text };
}
};
const App = {
setup() {
const count = ref(0);
const inc = () => {
count.value++;
};
return { count, inc };
}
}
Vue.createApp(App)
.component('SubComponent', SubComponent)
.mount('#app')
<head>
<script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
</head>
<body>
<div id="app">
<h1>Hello Vue 3!</h1>
<button @click="inc">Clicked {{ count }} times.</button>
<sub-component></sub-component>
</div>
</body>
You can't nest multiple vue apps, you only have one app and within it you can have multiple or nested components. Not sure with the approach having everything in one file though.
const {ref} = Vue;
const SubComponent = {
setup() {
const text = ref("");
return {
text
};
}
};
const App = {
components: {
SubComponent,
},
setup() {
const count = ref(0);
const inc = () => {
count.value++;
};
return {
count,
inc
};
}
}
Vue.createApp(App).mount('#app')
<head>
<script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
</head>
<body>
<div id="app">
<h1>Hello Vue 3!</h1>
<button @click="inc">Clicked {{ count }} times.</button>
<sub-component>
<h2>Hello from subcomponent</h2>
<input v-model="text" />
<br />
<span>{{text}}</span>
</sub-component>
</div>
</body>