Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
⌘K
Up or down tonavigateEnter toselectEscape toclose
On this page

Build a Vue.js App

Vue.js is a progressive front-end JavaScript framework. Itprovides tools and features for creating dynamic and interactive userinterfaces.

In this tutorial we'll build a simple Vue.js app with Vite and Deno. The appwill display a list of dinosaurs. When you click on one, it'll take you to adinosaur page with more details. You can see thefinished app on GitHub.

You can see a live version of the app onDeno Deploy.

Deploy your own

Want to skip the tutorial and deploy the finished app right now? Click thebutton below to instantly deploy your own copy of the complete Vue.js dinosaurapp to Deno Deploy. You'll get a live, working application that you cancustomize and modify as you learn!

Deploy on Deno

Create a Vue.js app with Vite and DenoJump to heading

We'll useVite to scaffold a basic Vue.js app. In yourterminal, run the following command to create a new .js app with Vite:

deno run-A npm:create-vite

When prompted, give your app a name and selectVue from the offered frameworksandTypeScript as a variant.

Once created,cd into your new project and run the following command toinstall dependencies:

denoinstall

Then, run the following command to serve your new Vue.js app:

deno task dev

Deno will run thedev task from thepackage.json file which will start theVite server. Click the output link to localhost to see your app in the browser.

Configure the formatterJump to heading

deno fmt supports Vue files with the--unstable-componentflag. To use it, run this command:

denofmt --unstable-component

To configuredeno fmt to always format your Vue files, add this at the toplevel of yourdeno.json file:

"unstable":["fmt-component"]

Add a backend APIJump to heading

We'll build an API server using Deno and Oak. This will be where we get ourdinosaur data.

In the root directory of your project, create anapi folder. In that folder,create adata.json, which will contain the hard coded dinosaur data.

Copy and pastethis json fileinto theapi/data.json file. (If you were building a real app, you wouldprobably fetch this data from a database or an external API.)

We're going to build out some API routes that return dinosaur information. We'llneed Oak for the HTTP server andCORS middleware to enableCORS.

Add the dependencies to yourdeno.json file by updating the imports section:

deno.json
{"imports":{"@oak/oak":"jsr:@oak/oak@^17.1.5","@tajpouria/cors":"jsr:@tajpouria/cors@^1.2.1","vue-router":"npm:vue-router@^4.5.1"}}

Next, createapi/main.ts and import the required modules and create a newRouter instance to define some routes:

api/main.ts
import{ Application, Router}from"@oak/oak";import{ oakCors}from"@tajpouria/cors";import routeStaticFilesFromfrom"./util/routeStaticFilesFrom.ts";import datafrom"./data.json"with{ type:"json"};exportconst app=newApplication();const router=newRouter();

After this, in the same file, we'll define two routes. One at/api/dinosaursto return all the dinosaurs, and/api/dinosaurs/:dinosaur to return a specificdinosaur based on the name in the URL:

api/main.ts
router.get("/api/dinosaurs",(context)=>{  context.response.body= data;});router.get("/api/dinosaurs/:dinosaur",(context)=>{if(!context?.params?.dinosaur){    context.response.body="No dinosaur name provided.";}const dinosaur= data.find((item)=>    item.name.toLowerCase()=== context.params.dinosaur.toLowerCase());  context.response.body= dinosaur??"No dinosaur found.";});

At the bottom of the same file, attach the routes we just defined to theapplication. We also must include the static file server, and finally we'llstart the server listening on port 8000:

api/main.ts
app.use(oakCors());app.use(router.routes());app.use(router.allowedMethods());app.use(routeStaticFilesFrom([`${Deno.cwd()}/dist`,`${Deno.cwd()}/public`,]));if(import.meta.main){console.log("Server listening on port http://localhost:8000");await app.listen({ port:8000});}

You'll also need to create theapi/util/routeStaticFilesFrom.ts file to servestatic files:

api/util/routeStaticFilesFrom.ts
import{ Context, Next}from"@oak/oak";// Configure static site routes so that we can serve// the Vite build output and the public folderexportdefaultfunctionrouteStaticFilesFrom(staticPaths:string[]){returnasync(context: Context<Record<string, object>>, next: Next)=>{for(const pathof staticPaths){try{await context.send({ root: path, index:"index.html"});return;}catch{continue;}}awaitnext();};}

You can run the API server withdeno run --allow-env --allow-net --allow-read api/main.ts. We'll create a taskto run this command in the background and update the dev task to run both theVue app and the API server.

Update yourpackage.json scripts to include the following:

package.json
{"scripts":{"dev":"deno task dev:api & deno task dev:vite","dev:api":"deno run --allow-env --allow-net api/main.ts","dev:vite":"deno run -A npm:vite","build":"deno run -A npm:vite build","server:start":"deno run -A --watch ./api/main.ts","serve":"deno run build && deno run server:start","preview":"vite preview"}}

Make sure yourvite.config.ts includes the Deno plugin and proxy configurationfor development:

vite.config.ts
import{ defineConfig}from"vite";import vuefrom"@vitejs/plugin-vue";import denofrom"@deno/vite-plugin";exportdefaultdefineConfig({  server:{    port:3000,    proxy:{"/api":{        target:"http://localhost:8000",        changeOrigin:true,},},},  plugins:[vue(),deno()],  optimizeDeps:{    include:["react/jsx-runtime"],},});

If you runnpm run dev now and visitlocalhost:8000/api/dinosaurs, in yourbrowser you should see a JSON response of all of the dinosaurs.

Build the frontendJump to heading

The entrypoint and routingJump to heading

In thesrc directory, you'll find amain.ts file. This is the entry pointfor the Vue.js app. Our app will have multiple route, so we'll need a router todo our client-side routing. We'll use the officialVue Router for this.

Updatesrc/main.ts to import and use the router:

import{ createApp}from"vue";import routerfrom"./router/index.ts";import"./style.css";import Appfrom"./App.vue";createApp(App).use(router).mount("#app");

Add the Vue Router module to the project by updating yourdeno.json imports:

deno.json
{"imports":{"@oak/oak":"jsr:@oak/oak@^17.1.5","@tajpouria/cors":"jsr:@tajpouria/cors@^1.2.1","vue-router":"npm:vue-router@^4.5.1"}}

Next, create arouter directory in thesrc directory. In it, create anindex.ts file with the following content:

router/index.ts
import{ createRouter, createWebHistory}from"vue-router";import HomePagefrom"../components/HomePage.vue";import Dinosaurfrom"../components/Dinosaur.vue";exportdefaultcreateRouter({  history:createWebHistory("/"),  routes:[{      path:"/",      name:"Home",      component: HomePage,},{      path:"/:dinosaur",      name:"Dinosaur",      component: Dinosaur,      props:true,},],});

This will set up a router with two routes:/ and/:dinosaur. TheHomePagecomponent will be rendered at/ and theDinosaur component will be renderedat/:dinosaur.

Finally, you can delete all of the code in thesrc/App.vue file to and updateit to include only the<RouterView> component:

App.vue
<template><RouterView/></template>

The componentsJump to heading

Vue.js splits the frontend UI into components. Each component is a reusablepiece of code. We'll create three components: one for the home page, one for thelist of dinosaurs, and one for an individual dinosaur.

Each component file is split into three parts:<script>,<template>, and<style>. The<script> tag contains the JavaScript logic for the component,the<template> tag contains the HTML, and the<style> tag contains the CSS.

In the/src/components directory, create three new files:HomePage.vue,Dinosaurs.vue, andDinosaur.vue.

The Dinosaurs componentJump to heading

TheDinosaurs component will fetch the list of dinosaurs from the API we setup earlier and render them as links using theRouterLink component from Vue Router.(Because we are making a TypeScript project, don't forget to specify thelang="ts" attribute on the script tag.) Add the following code to theDinosaurs.vue file:

Dinosaurs.vue
<scriptlang="ts">import{ defineComponent}from"vue";exportdefaultdefineComponent({asyncsetup(){const res=awaitfetch("/api/dinosaurs");const dinosaurs=await res.json()as Dinosaur[];return{ dinosaurs};},});</script><template><spanv-for="dinosaur in dinosaurs":key="dinosaur.name"><RouterLink:to="{ name: 'Dinosaur', params: { dinosaur: `${dinosaur.name.toLowerCase()}` } }">      {{ dinosaur.name }}</RouterLink></span></template>

This code uses the Vue.jsv-for directive toiterate over thedinosaurs array and render each dinosaur as aRouterLinkcomponent. The:to attribute of theRouterLink component specifies the routeto navigate to when the link is clicked, and the:key attribute is used touniquely identify each dinosaur.

The Homepage componentJump to heading

The homepage will contain a heading and then it will render theDinosaurscomponent. Add the following code to theHomePage.vue file:

HomePage.vue
<scriptsetuplang="ts">import Dinosaursfrom"./Dinosaurs.vue";</script><template><h1>Welcome to the Dinosaur App! 🦕</h1><p>Click on a dinosaur to learn more about them</p><Suspense><template#default><Dinosaurs/></template><template#fallback><div>Loading...</div></template></Suspense></template>

Because theDinosaurs component fetches data asynchronously, use theSuspense component tohandle the loading state.

The Dinosaur componentJump to heading

TheDinosaur component will display the name and description of a specificdinosaur and a link to go back to the full list.

First, we'll set up some types for the data we'll be fetching. Create atypes.ts file in thesrc directory and add the following code:

types.ts
typeDinosaur={  name:string;  description:string;};typeComponentData={  dinosaurDetails:null| Dinosaur;};

Then update theDinosaur.vue file:

Dinosaur.vue
<scriptlang="ts">import{ defineComponent}from"vue";exportdefaultdefineComponent({props:{dinosaur: String},data(): ComponentData{return{dinosaurDetails:null,};},asyncmounted(){const res=awaitfetch(`/api/dinosaurs/${this.dinosaur}`,);this.dinosaurDetails=await res.json();},});</script><template><h1>{{ dinosaurDetails?.name }}</h1><p>{{ dinosaurDetails?.description }}</p><RouterLinkto="/">🠠 Back to all dinosaurs</RouterLink></template>

This code uses theprops option to define a prop nameddinosaur that will bepassed to the component. Themounted lifecycle hook is used to fetch thedetails of the dinosaur based on thedinosaur prop and store them in thedinosaurDetails data property. This data is then rendered in the template.

Run the appJump to heading

Now that we've set up the frontend and backend, we can run the app. In yourterminal, run the following command:

npm run dev

This will start both the Deno API server on port 8000 and the Vite developmentserver on port 3000. The Vite server will proxy API requests to the Deno server.

Visithttp://localhost:3000 in your browser to see the app. Click on adinosaur to see more details!

You can see a live version of the app onDeno Deploy.

The vue app in action

deno run serve

This will build the Vue app and serve everything from the Deno server onport 8000.

Build and deployJump to heading

We set up the project with aserve task that builds the React app and servesit with the Oak backend server. Run the following command to build and serve theapp in production mode:

deno run builddeno run serve

This will:

  1. Build the Vue app using Vite (output goes todist/)
  2. Start the Oak server which serves both the API and the built Vue app

Visitlocalhost:8000 in your browser to see the production version of the app!

You can deploy this app to your favorite cloud provider. We recommend usingDeno Deploy for a simple and easy deploymentexperience. You can deploy your app directly from GitHub, simply create a GitHubrepository and push your code there, then connect it to Deno Deploy.

Create a GitHub repositoryJump to heading

Create a new GitHub repository, then initialize andpush your app to GitHub:

git init-b maingit remoteadd origin https://github.com/<your_github_username>/<your_repo_name>.gitgitadd.git commit-am'my vue app'git push-u origin main

Deploy to Deno DeployJump to heading

Once your app is on GitHub, you candeploy it to Deno Deploy.

For a walkthrough of deploying your app, check out theDeno Deploy tutorial.

🦕 Now that you can run a Vue app in Deno with Vite you're ready to build realworld applications!

Did you find what you needed?

What can we do to improve this page?

If provided, you'll be @mentioned in the created GitHub issue

Privacy policy

[8]ページ先頭

©2009-2025 Movatter.jp