Import and Export
Each file of a Vue app is a module: a part of the program with its own variables. What a module creates exists only in that module, so App.vue can't see the variables of another file. A file shares a value by exporting it, and the file that needs the value imports it. You've written import lines since the first lesson. Here's how they work.
A file can have one default export, its main value, written with export default. It's imported without curly braces, under a name that the importing file chooses:
// cafe.js
const menu = [
{ id: 1, name: "Espresso", price: 2 },
{ id: 2, name: "Cappuccino", price: 3 },
];
export default menu;// App.vue
import menu from "./cafe.js";A file can also export any number of values under their names, with export in front of const. These named exports are imported in curly braces, under their exact names, separated by commas:
// cafe.js
export const cafeName = "Corner Café";
export const openingHours = "7 am to 7 pm";// App.vue
import { cafeName, openingHours } from "./cafe.js";When a file has both, one import can get both: the default export first, then the named ones in braces, import menu, { cafeName } from "./cafe.js";. Braces where there should be none, or the other way round, are a common mistake: the import then doesn't find the value, and the page shows nothing in its place. (In a project on your own computer, the browser stops at such an import instead, with an error that the file “does not provide an export named …”.)
Now you can read every import you've seen:
import { ref } from "vue";imports the named exportrefof the packagevue. A name without./is a package, a library installed in the project.import App from "./App.vue";inmain.jsimports the default export ofApp.vue: the component.import "./style.css";imports nothing by name. It just adds the stylesheet to the page.
But where's the export in App.vue? You don't write it: <script setup> exports the component for you, as the file's default export. That's why import MenuItem from "./MenuItem.vue"; has no braces. And <script setup> can't have exports of its own; the red bar would say <script setup> cannot contain ES module exports. Values that several components need go into a .js file, such as cafe.js here.
And the extension? Vite, the tool that runs Vue projects on your computer, finds a .js file even without it, but a .vue file only with it. To keep it simple, write it in every import of your own files.
Instructions
- 1
Run the code: the heading is empty, and the console says
[Vue warn]: Property "cafeName" was accessed during render but is not defined on instance.The values are incafe.js, which doesn't export them. ExportcafeNameandopeningHoursfromcafe.jsby name, and import both inApp.vuewith one import. - 2
Make
menuthe default export ofcafe.js: writeexport default menu;at the end of the file. Import it inApp.vueunder the namemenu. The list shows the whole menu.