Vue is simply manipulate html with javascript.In basic you create a vue object and You mount that object on a div with an id.I wanted to test that i create a .vue file and import this .vue file to a js file and mount it on a div. But it fails. This project is just for trying. This is my project schema.
App.vue content :
<template>
<h1>{{ msg }}</h1>
<h1>.Vue file</h1>
</template>
<script>
export default{
name: 'App',
data(){
return{
msg: 'VUE JS 3'
}
}
}
</script>
app.js content :
import App from './App.vue';
const app = Vue.createApp(App);
app.mount('#app');
index.html content :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Basics</title>
<link
href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="https://unpkg.com/[email protected]/dist/vue.global.js" defer></script>
<script src="app.js" defer></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
when i add type="module" to script tag of app.js output is :
when i change type="module" to type="application/octet-stream", there is no error in console but nothing on web page.
I think i can not import a .vue file or .vue file is not working when i import it but why?
2
Answers
I already read these but my question is not this. When you use createApp function of Vue package, you are giving a vue element as an argument for this function. I was trying to create .vue file and import it to a .js file, this will be also a Vue element. Theoretically this should work too beacuse createApp function just want a vue element as a parameter. I've been researching this for a while and this is what I found out: It is not about vue, it is about webpack or project development tools. You need import .vue file as a module but if project has not a webpack or something like this tool, you can not import it as a module. When we use Vue from CDN, we are just integrate vue but we don't install any webpack so project can not handle .vue file and can not import a .vue file to .js file. If we want to import a .vue file to a .js file we should use webpack or vue cli or some tools like these.These tools allow you to handle .vue files properly and integrate them into your project. Vue CLI or webpack enables you to import .vue files into your .js files, thus allowing you to define Vue components in separate .vue files and then use them in your .js files. I hope i could explain my answer clear.
You can simulate this by specifying a
<template>
that contains the HTML of theApp
component. and inject it into the#app
DOM element.Here is an alternative approach, that keeps the App.vue component in-tact.