Get started quickly with VUE —vue project structure (api, assets, components, router, services, store, styles, views, App.vue, main.js)

vue project structure

Structure display

myapp/
├── public/ # Public resource directory
│ ├── index.html # Entry HTML file of the project
│ └── favicon.ico # Website icon
│
├── src/ # Project source code directory
│ ├── api/ # Define and manage the directory of modules or services that send requests to the backend server
│ ├── assets/ # Static resource directory
│ ├── components/ # Store component directory
│ ├── router/ # Routing configuration directory
│ ├── services/ # Same as api/same function
│ ├── store/ # Global status management directory
│ ├── styles/ # Same function as assets/
│ ├── views/ # Page component directory
│ ├── App.vue # Root component
│ └── main.js # Project entry file
│
├── .eslintrc.js # ESLint configuration file
├── babel.config.js # Babel configuration file
├── package.json # Project configuration file
└── README.md # Project description file

When starting a Vue project, you can follow the following steps:

  1. Understand the project structure: Check the directory structure in the project folder and understand the purpose of the main files and folders, such as package.json, src, etc.
  2. View the entry file: Find the main entry file, usually src/main.js or src/App.vue. These files define the configuration and routing of the Vue instance.
  3. Check the routing configuration: If Vue Router is used in the project for routing management, check src/router/index.js or other customized routing configuration files to understand the relationship between routing configuration and page components.
  4. View the component directory: Enter the src/components folder, view the components in the project, and understand the role and relationship of each component.
  5. View page files: Enter the src/views folder, view the page files in the project, and understand the content and structure of each page.
  6. Check API requests: If the project involves API requests, check the src/api or src/services folders to understand the configuration and processing logic of the API requests.
  7. View state management: If Vuex is used in the project for state management, view the src/store folder to understand the configuration and modular organization of state management.
  8. View style files: View the src/assets or src/styles folder to learn about the style files used in the project.

src/App.vue

A standard src/App.vue might look like this:

<template>
  <div id="app">
    <!-- Use Vue Router to render different pages -->
    <router-view />
  </div>
</template>

<script>
//Introduce components or tools
import VueRouter from 'vue-router';
import Home from './views/Home.vue';

export default {
  // Using the Vue Router plug-in, the router will be instantiated and injected into the component here, and the matched component will be displayed through <router-view/>
  router: new VueRouter({ // Create a router instance
    routes: [
      {
        path: '/', // The component corresponding to route `/` is `Home`
        component:Home
      }]})
}
</script>

<style>
/* Style details defined here */
</style>

The App.vue file serves as the root component of the project and is the parent component of all other components. It plays the role of connecting other components in the Vue project, defines the overall structure and style of the project, and provides support for routing and state management.

src/main.js

A standard src/main.js might look like this:

import Vue from 'vue'; // Import Vue module
import App from './App.vue'; // Import the root component App.vue
import router from './router'; // Import routing instance, used to manage the routing of the page
import store from './store'; // Import Vuex instance for global state management

Vue.config.productionTip = false; // Configure the prompt information for the production environment. Setting it to false can disable the production mode prompt.

new Vue({<!-- -->
  el: '#app', // The el option specifies the element to be mounted by the application. Here is the element with the id "app"
  router, // Inject routing instance to make routing function effective
  store, // Inject the Vuex instance to make the global state management function effective
  render: (h) => h(App), // Render the root component App.vue, h is the alias of createElement, used to create VNode (virtual node)
}).$mount('#app'); // Mount the Vue instance to the #app element and render it as the root node

The role of the main.js file in the Vue project is to create Vue instances, introduce plug-ins and libraries, register global components, configure global settings, etc. It is the entry file for the entire application, so that the entire Vue application can function normally run.

src/router/index.js

A standard src/router/index.js might look like this:

//Import the components you need to use
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue'; // Import components named Home, About, and Contact
import About from '../views/About.vue';
import Contact from '../views/Contact.vue';

Vue.use(VueRouter); // Declare Vue to use the Vue Router plug-in

const routes = [ // Define a routing array, which contains the components corresponding to each path.
  {<!-- -->
    path: '/', // path
    name: 'Home', // name
    component: Home // Corresponding component
  },
  {<!-- -->
    path: '/about',
    name: 'About',
    component: About
  },
  {<!-- -->
    path: '/contact',
    name: 'Contact',
    component: Contact
  }
];

const router = new VueRouter({<!-- --> // Use the VueRouter constructor to create a new routing instance
  mode: 'history', // Routing mode, which can be 'hash' or 'history'
  base: process.env.BASE_URL, // Base URL, used to deploy to different routing paths
  routes // routing configuration
});

export default router; // Export routing instance

The role of the src/router/index.js file in the Vue project is to define the routing configuration of the project. It exports a route instance that is used to manage switching and navigation between different routes in the project. He can also define the routing rules required for the project, including routing paths, corresponding components, whether authentication is required, and other information. You can also configure the navigation guard of the route to perform some logical operations before and after route switching, such as permission verification, route interception, etc.

In short, the src/router/index.js file plays the role of defining and managing routing in the Vue project, and is a key file to implement the front-end routing function.

src/components

A standard file under src/components might look like this:

<template>
  <div>
    <h1>{<!-- -->{ message }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: "Hello World!"
    };
  }
};
</script>

<style scoped="">
h1 {
  color: blue;
}
</style>

In a Vue project, the src/components folder is usually used to store Vue components and plays a role in storing and managing Vue components.

Vue components are the basic building blocks of Vue.js applications. They encapsulate a reusable, self-contained code block that can create and organize various functional components, such as buttons, navigation bars, forms, and information card sections. etc., responsible for combining them into a complete page component.

src/views

A simple login page component file under standard src/views might look like this:

//Introduce dependencies
import Vue from 'vue';
import axios from 'axios'; //Introduce the axios library to send HTTP requests

<script>
//Export a Vue component object
export default {
  // component name
  name: 'LoginPage',
  
  // data
  data() {
    return {
      username: '',
      password: '',
      loading: false,
      error: ''
      // username and password will be bound to the input box of the login form, loading is used to mark whether the request is in progress, and error is used to display login error information
    };
  },
  
  // method
  methods: {
    // Define a method login() to handle the login operation. This method is called when the login button is clicked. Within this method, we first set loading to true to display the loading status. We then use axios to send an HTTP POST request to the "/api/login" interface, passing the username and password as the request body. If the request is successful, we will print the response data to the console and set loading to false. If the request fails, we print an error message and set loading to false and error to an appropriate error message.
    login() {
      //Set loading status
      this.loading = true;
      
      //Initiate a login request
      axios.post('/api/login', {
        username: this.username,
        password: this.password
      })
      .then(response => {
        // Successful login, processing response
        console.log(response.data);
        this.loading = false;
      })
      .catch(error => {
        // Handle errors
        console.error(error);
        this.loading = false;
        this.error = 'Login failed, please check username and password. ';
      });
    }
  }
};
</script>

<template>
  <div>
    <h1>User login</h1>
        <div>
            <label>username:</label>
            <input v-model="username" placeholder="username here">
        </div>
        <div>
            <label>password:</label>
            <input v-model="password" placeholder="password here">
        </div>
        <div>
            <button @click="login">Login</button>
        </div>
  </div>
</template>

In Vue projects, the src/views folder is usually used to store the project’s page components. Page components are Vue’s single-file components (.vue files), which contain templates, styles and logic code. Each page component usually corresponds to a page of the application and is used to display specific content and provide corresponding interactions.

The role of the src/views folder in the Vue project is to store the page components of the application. It is used to classify and organize the code of different pages to improve the maintainability and scalability of the code.

src/api or src/services

A standard file under src/api or src/services may look like this:

import axios from 'axios'; // Import the axios library for sending HTTP requests.

//Define a function named `getUser`, which accepts a parameter `userId`
export const getUser = (userId) => {<!-- -->
  // Use the `get()` method of axios to send a GET request. The requested URL is `/api/user/${userId}`. Note that the ES6 string template syntax is used here, and `${userId}` will be replaced with the value of the actual `userId` parameter.
  return axios.get(`/api/user/${<!-- -->userId}`);
};

// Define a function named `updateUser`, which accepts two parameters `userId` and `newData`.
export const updateUser = (userId, newData) => {<!-- -->
  // Use axios to send a PUT request to update the specified user's information. The requested URL is `/api/user\${userId}` and the request body is `newData`
  return axios.put(`/api/user/${<!-- -->userId}`, newData);
};

In a Vue project, the src/api or src/services folder is usually used to manage code that communicates with the backend API. The code can include functions for making network requests, code for configuring request headers and interceptors, and code for response data. Function to perform processing.

src/store

In Vue projects, Vuex is usually used for state management and where Vuex-related code is stored.

src/assets or src/styles

Mainly to store some .gif, .png, .jpg, .ttf, .css format file.