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>
3
Answers
Short answer: save your component in another file and use a script tag to import it, the same way as you did with Vue.
Recomendation: usually people will bundle and package their JavaScript code before deploying. There are different tools for the job, but one option is Vite. Read more about it here: https://vitejs.dev/
Yes, you can create a js file at, for ex. `components/component1.js’, with the definition for your component.
Import that file in the html file with:
and the component will be available in script section.
You could try fetching the component as text and evaluating it.
Although using
eval
is dangerous and should be avoided.Note: This assumes that you are not assigning the object in the CDN resource. If you are, Igor’s suggestion of loading it as JS is a better approach.