search
HomeWeb Front-endJS TutorialDetailed explanation of Vue.js project API and Router configuration split practice

This article mainly introduces the detailed explanation of the Vue.js project API and Router configuration splitting practice. Now I will share it with you and give you a reference.

Separate front-end and back-end development methods. The front-end has higher control.

With the rapid development of front-end framework technology, the concept of Router has also been rapidly popularized in front-end projects. , in the early period when there was no separation, there was no clear concept of routing. Most front-end page jumps were forwarded through the back-end. For example, in the Spring MVC project, a page jump is as follows (red line part) :


The front end needs a hyperlink, the link's href=/manager, so that the hyperlink is forwarded to the page specified by the scs/waitFollowed path.

After the separation of front and back, the way of front-end page jump has changed. Back-end processing is no longer needed, and the data exchange method has also changed. Therefore, the front-end needs to define Router configuration files and API configuration files. . In the permission configuration management of the project, there is no need for the back-end at all. It can be said that the permission configuration table can be taken out separately and maintained by the front-end.

For example, this url field depends heavily on the backend when the frontend and backend are not separated. The url is the backend interface address. If it needs to be changed, it needs to be changed. The backend modifies the code to modify the interface address, and now the frontend can freely control the value of the url.

At the interface level, the front end will also have its own configuration file, and the interfaces provided by the back end can be renamed, combined, etc. For example,

the front-end is managed uniformly using module name interface name. It doesn’t matter what the interface provided by the back-end is called. It is more convenient both visually and in maintenance. When used on the page, the query is also very intuitive:

You will know this when you see the interface DISTRBUTE().Leads.dataGrid It is the list query interface under the Leasd function under the DISTRBUTE module

API and Router configuration in Vue.js

Under the Vue.js project, we only use one api.config.js configuration file at the beginning. All interfaces are defined in it, and the router is the same, all configured in one router.config .js, the following is the API configuration file in our project

You can see that many business modules and many interfaces have reached 570 Multiple lines. As the business further advances, the interface expands rapidly and the file becomes larger and larger.

At this time, there is an urgent need to split the different business modules into individual API configuration files. Similarly, let’s take a look at the Router configuration file before splitting:

#The biggest disadvantage of having one and more routers is that it will lead to router naming conflicts.

Split! Split! Split!

First consider how to split the API configuration file. For the interface, we must have multiple sets of environments. If there are multiple sets of environments, the API URLs will be different. After splitting into multiple files, multiple files need They share the same method of obtaining apiBase, so this apiBase must be written in a public place, where the original api.config.js becomes Public configuration, apiBase is placed in this file.

export function apiBase() {
 let hostname = window.location.hostname,
  API_BASE_URL = 'http://test2api.dunizb.com';//默认环境
 if(hostname === 'crm.dunizb.cn') { //正式环境
  API_BASE_URL = 'http://api.dunizb.cn';
 } else if(hostname === 'admin.dunizb.com') {//公网测试环境
  API_BASE_URL = 'http://testapi.dunizb.com';
 } else if(hostname === 'manager.dunizb.com') {//内网测试环境
  API_BASE_URL = 'http://test2api.dunizb.com';
 }
 return API_BASE_URL;
}

Then introduce it in each sub-API configuration file:

import {apiBase} from '../api.config';

The specific function API does not need to be changed, just copy the corresponding module API to the sub-module API configuration file.

Router splitting is a little more complicated. The split file directory is the same as the API directory:

The idea of ​​splitting is exactly the same, but make sure there is only one router.startThat is:

return router.start(App, '#app');

Although you Writing the page in the sub-router configuration file will work normally, but Vue.js will report an error in the console:

这个错误的意思就是router已经启动,无需启动多次。所以,子router文件中不能存在 return router.start(App, '#app'); 这样的代码。

拆分后router.config.js内容如下:

/**
 * 路由总文件
 * Created by Bing on 2017/6/19 0019.
 */
import App from './App';
import authority from './routers/authority';
import publics from './routers/public';
import study from './routers/study';
... ...
export default function(router){
 authority(router);//基础与权限模块
 publics(router);//公共模块
 study(router);//教学相关
 ... ...
 return router.start(App, '#app');
}

而子router配置文件的写法就是这样(以study模块为例):

/**
 * 教学排课
 * 教研
 * Created by Bing on 2017/6/19 0019.
 */
import courseIndex from 'components/studyCourse/index/index';
import waitCourse from 'components/studyCourse/waitCourse/waitCourse';
import alreadyCourse from 'components/studyCourse/alreadyCourse/alreadyCourse';
import gearCourse from 'components/studyCourse/waitCourse/gearCourse';
import courseWare from 'components/teachingResearch/courseware/courseware.vue';
import courseWareLibrary from 'components/teachingResearch/courseware/library.vue';
export default function(router) {
 router.map({
  '/study/index': {component: courseIndex},
  '/study/waitCourse': {component: waitCourse},//待排课程
  '/study/waitCourse/gearCourse': {component: gearCourse},//待排
  '/study/course': {component: alreadyCourse},//已排课程
  '/tr/courseware': {component: courseWare},//课件管理
  '/tr/courseWare/library': {component: courseWareLibrary},//自主上传课件库
 });
}

拆分后,每个模块管理它自己领域的router、api,router.config.js和api.config.js就大大瘦身了,也降低了命名冲突的问题和将来混乱的问题。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

js传递数组参数到后台controller的方法

Vue.js 表单控件操作小结

Vue.js实现可配置的登录表单代码详解

The above is the detailed content of Detailed explanation of Vue.js project API and Router configuration split practice. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment