Vue development large project code writing specification-advanced front-end must-see

Now the project development is basically done by the team, and the current development model of separation of front and back ends is adopted. There are more people and each person's code style is different, which leads to a messy project and maintenance after the later personnel leave. And iterative development is fatal, so it is necessary for the team to follow a common specification. With a unified specification, you can ensure that the project created by the team can still be easily maintained and iteratively developed a few years later.


Code style must be unified and standardized

Example: Look at the following code specification, each vue file has mounted and methods in it, so your code has to be written like this. To save the this variable, the entire team uses vm. This is a unified team specification to enhance the readability of the code. Why save this? Because the this point may be problematic in arrow functions and nested function calls. The page data acquisition team obtains it in mounted, of course, you can also in created, but there must be a unified specification, and everyone's initialization data is obtained in the same place. If you do this in the future, the people in the team will use the components written by others. His initialization will only look at mounted, and see which methods are executed during initialization.

mounted() {
    
    
	let vm = this; 
	vm.init(); // 页面初始化的数据都在这个方法里执行
},
methods: {
    
    
	init() {
    
    
		let vm = this;
		vm.initData(); // 获取页面初始化数据
		vm.getDetail(); // 获取页面需要的详细信息
	},
	// 页面中的方法命名也必须统一,见名知意,不能个性化,统一的命名规范十分方便以后维护以及功能迭代
	initData() {
    
    
	},
	getDetail() {
    
    
	}
}

In addition, eslint must be used to verify the code in team projects, so as to standardize the format of all developers' code.

Necessary methods, parameters, and custom flags should be commented to improve code readability and reduce future maintenance costs.

The code is as follows (example):

data() {
    
    
	return {
    
    
		routeFlag: 'add' // add为新增,review为复核,back为打回重新申请,update为更新操作,overdue为过期
	}
},
methods: {
    
    
	// 用户信息提交,type == 1,新增操作,type == 2,变更操作, type == 3,提交到其他系统审核
	handeSubmit(type) {
    
    
		// 过滤用户id信息
		peopleArray.filter((item) => {
    
    
			return item.id == fromData.id;
		});
	}
}

Encapsulation and placement of framework public resources

At the beginning of the project, you must first determine which technology to use and what framework to use, and then based on this framework, encapsulate a framework for teams that meet the needs of enterprise development. Take vue as an example. You need to build a http.js in its src directory. This file is mainly to import axios, then intercept the request and response, and set the common request header, and then the unified processing of the request parameters. After the processing is completed It is best to mount the axios-based get, post, getJson, postJson and other methods to the vue instance prototype, that is, vue.prototype.get = self-encapsulated function, the project can directly call this.get get request. Of course, this http.js file must be introduced in main.js.

Then you have to create an api folder under src, and some sub-module folders are being built underground, which are the interfaces and data acquisition methods required by each module.

There should also be a utils folder under src, where some common tools and functions of the system are stored, such as time formatting function, decimal point interception, money conversion, mobile phone mailbox format verification, object cloning and other common public functions. Developers The user can be directly introduced on the page to avoid n developers writing n time formatting functions in n locations.
The style folder built under src is used to store some public styles in the system. An index.scss is built in it, and table.scss (table public style) and detail.scss (detail page public style) are introduced into index.scss. Also have the idea of ​​modular development.

The project uses vuex to manage some data, establishes corresponding modular data in the store, and introduces all modules to use in the index. It is better to define uppercase constants for mutaions and actions in vuex to avoid changing the data later. In fact, some user data in vuex needs to be locally persisted, such as user basic information and token, as well as the language selected by the user, because only the js file is running before the data is available, but when the browser is refreshed, the file is reloaded , The data in vuex disappears, so you can use the vue-persistence plugin to do data persistence.

The routing file must use asynchronous loading to import components, use require or component: () => import('@/views/404'), component asynchronous is actually a function assignment process, only you execute the current component, the function The components are introduced only after execution. This method solves the problem of large project components. If all components are loaded, it may take a year (just kidding, the main expression is that it is too slow to load multiple components simultaneously). In the routing file, the global routing guard is used for the operations of users who are not logged in. The code is as follows:

// 全局路由守卫
router.beforeEach(function (to, from, next) {
    
    
  if (to.matched.length === 0) {
    
    
    // 判断此跳转路由的来源路由是否存在,存在的情况跳转到来源路由,否则跳转到404页面
    next('/404');
  } else {
    
    
    // 浏览器刷新,vuex中数据消失,从本地缓存拿
    // userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}, 这是store中的userInfo获取,看本地是否有,有的话拿本地数据
    let token = store.state.userInfo.token;
    // meta标签中标记路由是否要登陆 isLogin
    if (to.meta.isLogin) {
    
    
      if (token) {
    
    
        next();
      } else {
    
    
        next('/login');
      }
    } else {
    
    
      next();
    }
  }
});

Write a layout in the views folder to initialize the sidebar, navbar and main of the project. This can directly use the layout in the element. The specification of the navigation bar is written as follows (each route is obtained by traversal, and the routing array can be requested according to user permissions Return routing array):

    <el-aside class="main_con" style="width:250px;">
      <el-menu :default-active="$store.state.treeState" unique-opened @open="handleOpen" @close="handleClose" class="el-menu-vertical-demo" :collapse="isCollapse" router text-color="#fff" background-color="#422c50">
        <template v-for="(item,index) in treeData">
          <el-submenu :index="item.router" v-if="item.childResource.length>0" :key="index">
            <template slot="title">
              <i :class="item.icon"></i>
              <span v-text="item.resName"></span>
            </template>
            <template v-for="(child,indx) in item.childResource">
              <el-menu-item :index="child.router" v-if="child.childResource.length==0" :key="indx">
                <template slot="title">
                  {
   
   {child.resName}}
                </template>
              </el-menu-item>
              <el-submenu :index="child.router" v-if="child.childResource.length>0" :key="child.resName">
                <template slot="title">
                  {
   
   {child.resName}}
                </template>
                <el-menu-item :index="child.router" v-for="(child,idx) in child.childResource" :key="idx">
                  {
   
   {child.resName}}
                </el-menu-item>
              </el-submenu>
            </template>
          </el-submenu>
          <el-menu-item :index="item.router" v-if="item.childResource.length==0" :key="index">
            <i :class="item.icon"></i>
            <span slot="title" v-text="item.resName"></span>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>

data() {
	return {
		treeData: [{
			'icon': 'el-icon-s-home',
	        'resName': '首页',
	        'router': '/platformManage/home/home',
	        'childResource': []},{
        		'icon': 'el-icon-tickets',
		        'resName': '列表',
		        'router': '/platformManage/list/list',
		        'childResource': [
		          {
		            'icon': 'el-icon-tickets',
		            'resName': '列表页',
		            'router': '/platformManage/list/list',
		            'childResource': []
		          }, {
		            'icon': 'el-icon-tickets',
		            'resName': '预授权码列表',
		            'router': '/platformManage/applyOut/applyOut',
		            'childResource': []
		          }
		        ]
	        }
	    ]
	}
}

The purpose of component development is to simplify some complex functions, for function iteration and simple maintenance

Use the components reasonably in the project. What is reasonable use. For example, if there are a hundred functional pages, you can distribute it to 10 people, each responsible for ten, but if this is an individual, then subdivide it. , Each person has changed from ten to one hundred, which undoubtedly complicates the work, so you should use the idea of ​​componentization reasonably, don’t use components for the sake of using components!
If you want to be a senior For front-end development, you have to understand how webpack is packaged. It can recognize js modules and package other files. You will configure loder and third-party plugins. Vender.js is introduced in webpack so that third-party libraries will not be packaged after they are packaged once, because the code of third-party libraries will generally be changed, such as Jquery. Happypack is introduced in webpack to speed up the packaging speed, so that the program can carry out multiple packaging at the same time!

Guess you like

Origin blog.csdn.net/qq_42671194/article/details/108670341