Creating a Vue.js project is relatively straightforward. You can use Vue CLI (Command Line Interface) to quickly set up a new Vue project with a predefined directory structure, build system, and development server.
Here’s a step-by-step guide to creating a Vue project using Vue CLI:
-
Install Node.js and npm: Vue CLI requires Node.js and npm (Node Package Manager) to be installed on your machine. You can download and install them from the official Node.js website.
-
Install Vue CLI: Once you have Node.js and npm installed, you can install Vue CLI globally using npm. Open your terminal or command prompt and run the following command:
npm install -g @vue/cli
Create a new Vue project: After installing Vue CLI, you can create a new Vue project by running the following command:
vue create my-vue-project
-
Replace
my-vue-projectwith the name you want to give your project. This command will prompt you to pick a preset. You can choose the default preset or manually select features such as Vue Router, Vuex, CSS pre-processors, etc., based on your project requirements. -
Navigate to the project directory: Once the project has been created, navigate into the project directory using the following command:
cd my-vue-project
-
Replace
my-vue-projectwith the name you want to give your project. This command will prompt you to pick a preset. You can choose the default preset or manually select features such as Vue Router, Vuex, CSS pre-processors, etc., based on your project requirements. -
Navigate to the project directory: Once the project has been created, navigate into the project directory using the following command:
cd my-vue-project
Run the development server: To start the development server and preview your Vue application, run the following command:
npm run serve
-
This will start a development server and give you a URL where you can view your Vue application in the browser. By default, the URL is usually
http://localhost:8080.
That’s it! You’ve successfully created a new Vue project using Vue CLI. You can now start developing your Vue application by editing the files in the project directory.
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import Profile from '../views/Profile.vue';
import Product from '../views/Product.vue';
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/profile',
name: 'profile',
component: Profile,
},
{
path: '/product/:id',
component: Product
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;
This code sets up the router configuration for a Vue.js application using Vue Router. Let’s break it down step by step:
-
Imports:
- The code imports
createRouterandcreateWebHistoryfunctions from ‘vue-router’ package. - It imports the components
Home,Profile,Product, andAboutfrom their respective files.
- The code imports
-
Routes Configuration:
- The
routesarray contains an array of route objects. - Each route object specifies a
path, aname, and acomponent. - The
pathdefines the URL path for the route. - The
nameprovides a unique identifier for the route. - The
componentspecifies the Vue component to render when the route is matched.
- The
-
Dynamic Route:
- There is a dynamic route
/product/:id, where:idis a route parameter representing the product ID. - This route will render the
Productcomponent.
- There is a dynamic route
-
Lazy Loading:
- The route for
/aboutuses lazy loading. Instead of importing theAboutcomponent directly, it uses a function that imports the component asynchronously when the route is visited. This helps to reduce the initial bundle size of the application.
- The route for
-
Router Creation:
- The
createRouterfunction is called to create a router instance. - It takes an object with
historyandroutesproperties as arguments. createWebHistoryis used to create a history instance for the browser history.- The
process.env.BASE_URLis used as the base URL for the history instance. - The
routesarray defined earlier is passed to theroutesproperty.
- The
-
Export:
- The
routerinstance created is exported as the default export of the module, making it accessible to other parts of the Vue application.
- The
Overall, this code configures the router for the Vue.js application, defining routes and associating them with corresponding components. It also enables lazy loading for certain routes to optimize performance.
//src/App.vue
<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<!--<router-link to="/profile">Profile</router-link> -->
<router-link :to="{ name: 'profile', params: { username: 'cairocoders' } }" > <!--router params -->
Profile
</router-link> |
<router-link to="/product">Product</router-link>
</div>
<router-view/>
</template>
This code represents the template part of the main Vue component (App.vue) in a Vue.js application. Let’s break it down:
-
Template Structure:
- The template starts with a
<div>element with the id “nav”. - Inside the div, there are several
<router-link>elements used for navigation. - Below the navigation links, there’s a
<router-view>element. This is where the components corresponding to the current route will be rendered.
- The template starts with a
-
Router Links:
<router-link>components are used to create navigation links.- Each
<router-link>represents a link to a specific route in the application. - The
toprop specifies the target route for the link. - In the provided code:
- There are links to the “Home”, “About”, “Profile”, and “Product” routes.
- The “Profile” link demonstrates the use of route parameters. It’s a dynamic link constructed with the
nameproperty set to ‘profile’ and theparamsproperty set to an object containing the username parameter. - The “Profile” link is currently commented out using Vue’s comment syntax (
<!-- ... -->).
-
Router View:
- The
<router-view>component is where the content of the current route will be rendered. - When the user navigates between routes, the component associated with the current route will be displayed in place of the
<router-view>.
- The
Overall, this template provides navigation links for different routes in the application and a placeholder (<router-view>) for rendering the content of the current route.
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
This code sets up the Vue.js application by creating the app instance and mounting it to the DOM. Let’s break it down:
-
Imports:
- The code imports the
createAppfunction from ‘vue’ package. This function is used to create a new Vue application instance. - It imports the
Appcomponent from ‘./App.vue’ and therouterfrom ‘./router’.
- The code imports the
-
Create Vue App:
- The
createAppfunction is called with theAppcomponent passed as an argument. This initializes a new Vue application instance. - The
usemethod is called on the created app instance, with therouterpassed as an argument. This installs the router into the application. - Finally, the
mountmethod is called on the app instance, which mounts the Vue application to the DOM element with the id “app”.
- The
-
Export:
- There’s no explicit export in this file. This file is typically used as the entry point of the Vue.js application.
Overall, this code initializes a Vue application, installs the router, and mounts the application to the DOM, rendering the App component.
//src/views/Product.vue
<template>
<div class="product">
Product Page
</div>
<span>
Looking for Product: {{ this.$route.params.id }}
</span>
</template>
This code represents the template part of a Vue component (Product.vue) used for displaying product information. Let’s break it down:
-
Template Structure:
- The template consists of a
<div>element with the class “product” and a<span>element. - Inside the
<div>, there’s a text “Product Page”, which is the main content of the component. - Below the
<div>, there’s a<span>element displaying dynamic content.
- The template consists of a
-
Dynamic Content:
- The
<span>element contains a piece of text that says “Looking for Product:” followed by a dynamic expression{{ this.$route.params.id }}. this.$route.params.idis a reference to the route parameter named “id” passed in the URL.- When this component is rendered for a route like “/product/123”, the value of
this.$route.params.idwill be “123”.
- The
-
Interpolation:
- The double curly braces
{{ ... }}denote Vue.js interpolation syntax, used to output dynamic data. - Inside the curly braces, expressions are evaluated and their results are rendered in the template.
- The double curly braces
Overall, this template renders the product page content and displays the value of the “id” route parameter in the text “Looking for Product:”. This allows the component to dynamically display information based on the current route parameters.
//src/views/Profile.vue
<template>
<div class="profile">
Profile Info
</div>
<span>
{{ this.$route.params.username }}
</span>
</template>
This code represents the template part of a Vue component (Profile.vue) used for displaying profile information. Let’s break it down:
-
Template Structure:
- The template consists of a
<div>element with the class “profile” and a<span>element. - Inside the
<div>, there’s a text “Profile Info”, which is the main content of the component. - Below the
<div>, there’s a<span>element displaying dynamic content.
- The template consists of a
-
Dynamic Content:
- The
<span>element contains a piece of text that displays the value of the “username” route parameter using interpolation{{ this.$route.params.username }}. this.$route.params.usernameis a reference to the route parameter named “username” passed in the URL.- When this component is rendered for a route like “/profile/:username”, the value of
this.$route.params.usernamewill be the actual username passed in the URL.
- The
-
Interpolation:
- The double curly braces
{{ ... }}denote Vue.js interpolation syntax, used to output dynamic data. - Inside the curly braces, expressions are evaluated and their results are rendered in the template.
- The double curly braces
Overall, this template renders the profile information and dynamically displays the username based on the current route parameters.