[Vue practical project] General management system: API packaging, 404 pages

Preface

This article is the third article in the blogger's series of practical Vue small projects. It is very suitable for back-end or those who are just getting started. It is a nanny-level teaching of a front-end project from 0 to 1. Previous content:

[Vue Practical Project] General Management System: Login Page-CSDN Blog

[Vue Practical Project] General Management System: Encapsulating token operations and network requests-CSDN Blog

Table of contents

1.api encapsulation

2.404 page

3.Discuss


1.api encapsulation

Since there are many APIs in a project, they are adjusted everywhere. If you follow the previous writing method and adjust the API in each component, once the API is changed, it must be changed everywhere, so the API should also be encapsulated and the API The calls are encapsulated in functions, and the functions are grouped together for easy management.

Create an api directory under src to store the api. Create an api.js in the api directory to encapsulate each api:

Since the project has only used one back-end API so far, namely login, the content of api.js here is as follows:

import service from '../utils/service'

export function login(data){
    return service({
        method:'post',
        url:'/login',
        data
    })
}

After extracting api.js, future back-end api calls will use the functions provided in api.js. Here, first change the api calling logic of the Login page:

import {setToken} from '@/utils/setToken.js'
import {login} from '@/api/api.js'
methods:{
    login(form){
      this.$refs[form].validate((valid)=>{
        if(valid){
          console.log(this.form)
          // this.service.post('/login',this.form)
          // .then(res=>{
          //   console.log(res.status)
          //   if(res.status===200){
          //     setToken('username',res.data.username)
          //     setToken('token',res.data.token)
          //     this.$router.push('/home')
          //   }
          // })
          login(this.form).then(res=>{
            console.log(res.status)
            if(res.status===200){
              setToken('username',res.data.username)
              setToken('token',res.data.token)
              this.$router.push('/home')
            }
          })
        }else{
          console.error(this.form)
        }
      })
    }
  }

After making the changes, you can try running the project and it will work normally.

2.404 page

Next, we develop the 404 page. The 404 page is a general page of the system. Any illegal requests will jump to the 404 page. We can refer to the practice of 404 pages in most systems now, which is a simple picture + a route to jump back to the home page.

Prepare the background image of the 404 page and create the new components of the 404 page:

Component code:

<template>
  <div class="background-container">
    <!-- Your page content goes here -->
    <div class="content">
      <div>页面不见了!</div>
        <div>首页瞧瞧,点击<router-link to="/">这里</router-link>进入首页.</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'YourComponent',
};
</script>

<style lang="less">
/* Scoped styles for the component */

.background-container {
  /* Adjust the path to your actual image file */
  background-image: url('../assets/404.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  margin: 0;
  padding: 0;
  height: 100vh; /* Set the height to 100% of the viewport height */
  display: flex;
  justify-content: center;
  align-items: center;
  .content {
  text-align: center;
}
}
</style>

Next is the key step to redirect all illegal requests to the 404 page - configure routing:

When a request comes in, it will first try to accurately match the route. If it cannot match, it will be handled by wildcards. Therefore, using wildcards in the path of the 404 page can achieve the effect of jumping to the 404 page from the access method page.

Routing configuration:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
    routes:[
        {
            path:'/',
            redirect:'/login',
            component: ()=>import('@/components/Login')
        },
        {
            path:'/login',
            name:'Login',
            component: ()=>import('@/components/Login')
        },
        {
            path:'/home',
            component: ()=>import('@/components/HelloWorld')
        },
        {
            path:'*',
            name:'NotFound',
            component:()=>import('@/components/NotFound')
        }
    ],
    mode:'history'
})

Finally look at the effect:

Access a non-existent path and jump to 404.

3.Discuss

Let’s discuss the value of crazy transfer api.js here (you can skip it directly):

In modern front-end development, encapsulating an independent api.js file is usually to better organize and manage data interaction between the front-end and back-end, and to uniformly manage API requests.

Here are some common reasons:

  1. Code organization and maintainability: Centralizing all API requests that communicate with the backend into a single file makes it easier to organize and maintain your code. This makes it easier for teams to find and modify API-related code.

  2. Manage API addresses centrally: Centrally manage all API addresses in api.js, making it easier for teams to manage and update these addresses. No need to do extensive find and replace throughout the application.

  3. Encapsulate request logic: In api.js, you can encapsulate some common request logic, such as interceptors for processing requests and responses, and the injection of authentication information. wait. This helps reduce duplication of code and improves code reusability.

  4. Easy to test: Encapsulating the API request logic into a file makes unit testing easier. You can focus on testing the api.js file to make sure it handles various request and response situations correctly.

  5. Adapt to different environments: In api.js you can set API addresses in different environments, such as development environment, test environment and production environment. This makes it more convenient when switching environments without having to manually change multiple files.

  6. Team collaboration: Abstracting API requests into a file can make it easier for teams to collaborate. Developers can focus on implementing pages and components without having to dig into the underlying API request details.

  7. Better error handling: In api.js, errors can be handled centrally, such as unified processing of error status codes, adding common error prompts, etc. Thus providing a better user experience.

In general, encapsulating an independent api.js file helps to improve the maintainability, testability and team collaboration efficiency of the code, and at the same time provides solutions for various scenarios. Better flexibility.

Guess you like

Origin blog.csdn.net/Joker_ZJN/article/details/134425895