The code is working, but I’d like to store my component outside of the HTML and then import it.
Ideally it should be in a component folder. Is it possible?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
</head>
<body>
<div id="app">
<test />
</div>
<script>
const component1 = {
template: `<div> <p>{{ item }}</p></div>`,
props: ['prop'],
data: () => ({ item: 'test' }),
}
const app = Vue.createApp({
data: () => ({ someData: 'prop' }),
})
app.component('test', component1)
app.mount('#app')
</script>
</body>
</html>
>Solution :
Yes, you can create a js file at, for ex. `components/component1.js’, with the definition for your component.
const component1 = {
template: `<div> <p>{{ item }}</p></div>`,
props: ['prop'],
data: () => ({ item: 'test' }),
}
Import that file in the html file with:
<script src="components/component1.js"></script>
and the component will be available in script section.
<script>
const app = Vue.createApp({
data: () => ({ someData: 'prop' }),
})
app.component('test', component1)
app.mount('#app')
</script>