Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the technologies implemented by the front-end architecture based on Vue

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the technologies realized by the front-end architecture based on Vue". In the daily operation, I believe that many people have doubts about the technology implemented by the front-end architecture based on Vue. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "what are the technologies realized by the front-end architecture based on Vue?" Next, please follow the editor to study!

1. Decompose demand

Technology stack

Considering the subsequent recruitment and the technology stack of existing staff, Vue is chosen as the framework.

The company's main business is GIS and BIM, usually developing some medium and large systems, so vue-router and vuex are essential.

Gave up Element UI and chose Ant Design Vue (recently Element seems to have been resurrected, Ma Egg).

Select lodash in the tool library.

Build scaffolding

Set up NPM private server.

Use the Node environment to develop CLI tools.

Build a basic template based on @ vue/cli (as you all know, saving development time is far better than building from scratch).

Define various functions that may be used in development according to business requirements (component library, state management, filter, instruction, CSS built-in variables, CSS Mixins, form validation, tool functions, etc.).

Performance optimization, such as optimization of the Ant Design Vue component library.

Development specification

Uniformly standardize the code style, naming rules and directory structure.

Specification for the use of static resources.

Unit test, submit online test specification.

Git submission record and multi-person collaboration specification.

two。 Style

Selection of CSS preprocessor

Sass/Scss ✅

Less ✅

Stylus ⭕

Why did you choose two? Because the company team tends to use scss development, less is to cover the style of ant design vue, and only I like this style of stylus.

Local style and global style

Local style

The scoped scheme is generally used:

... Copy the code

Global styl

Global style catalog: @ / styles

Variable.scss: global variable management mixins.scss: global Mixins management global.scss: global style

Where variable.scss and mixins.scss take precedence over global.css to load, and these variables and mixins can be used anywhere in the project without import.

/ / vue.config.js module.exports = {css: {loaderOptions: {sass: {prependData: `@ import'@ / styles/variable.scss'; @ import'@ / styles/mixins.scss';`,} copy the code

Experience optimization

Page loading progress bar

Use nprogress to make a pseudo-progress bar when a route is redirected, which lets the user know that the page is already loaded when the network is not good:

Import NProgress from 'nprogress'; router.beforeEach (() = > {NProgress.start ();}); router.afterEach (() = > {NProgress.done ();}); copy code

Beautify the scroll bar

When I have been using Mac as the front end, I suddenly found a very ugly scroll bar on my colleague's Windows, in order to be consistent:

::-webkit-scrollbar {width: 6px; height: 6px;}::-webkit-scrollbar-track {width: 6px; background: rgba (# 101F1C, 0.1);-webkit-border-radius: 2mm;-moz-border-radius: 2em; border-radius: 2em;}:-webkit-scrollbar-thumb {background-color: rgba (# 101F1C, 0.5); background-clip: padding-box; min-height: 28px -webkit-border-radius: 2em;-moz-border-radius: 2em; border-radius: 2em;}::-webkit-scrollbar-thumb:hover {background-color: rgba (# 101F1C, 1);} copy the code

Static resource load page

When the page is loaded for the first time, there will be a lot of white screen time, so making a loading effect will look very friendly, but it is actually very simple, just write some static styles in public/index.html.

Mobile 100vh problem

When using 100vh on mobile, it is found that the browser bar and some navigation bars and link bars cause different rendering in Chrome and Safari browsers:

You think 100vh = Viewport height

Actually 100vh = Viewport height + the height of the browser toolbar (address bar, etc.)

Solution

Install vh-check npm install vh-check\-- save

Import vhCheck from 'vh-check'; vhCheck (' browser-address-bar'); copy the code

Define a CSS Mixin

@ mixin vh ($height: 100vh) {height: $height; height: calc (# {$height}-var (--browser-address-bar, 0px);} copy the code

After that, there will be no place to order.

3. Component library

Because Element UI has not been updated for a long time and has previously used React's Ant Design (emphasis), the component library chose Ant Design Vue.

Override Ant Design Vue styl

In the eyes of designers, Ant Design = = 'ugly' (sad).

1. Use .less fil

Ant Design Vue style uses Less as the development language and defines a series of global / component style variables, so you need to install less and less-loader. The default style can be overridden in @ / styles/antd-theme.less.

The advantages are:

Quick and convenient, you can modify the class to override the default variable.

The disadvantages are:

@ import'~ ant-design-vue/dist/antd.less'; must be introduced, and all component styles will be introduced after introduction, resulting in a packaged css with a volume of about 500kb.

two。 Working with JavaScript objects

You can modify the built-in variables through the JavaScript object, and you need to configure Less:

/ / vue.config.js const modifyVars = require ('. / src/styles/antdTheme.js'); module.exports = {css: {loaderOptions: {less: {lessOptions: {javascriptEnabled: true, modifyVars,}, copy the code

This step can also be optimized so that the component styles of Ant Design Vue can be loaded on demand through babel-plugin-import:

/ / babel.config.js module.exports = {presets: ['@ vue/cli-plugin-babel/preset',], plugins: ['import', {libraryName:' ant-design-vue', libraryDirectory: 'es', style: true},],}; copy the code

The advantages are:

It can be introduced on demand, and the packaged CSS volume depends on how many components you reference.

The disadvantages are:

You cannot use class for style overrides.

Get rid of useless icons

Ant Design Vue introduces all the Icon at once (no matter how many components you use), which makes the volume packaged with icons take up hundreds of kb. Most of these icons will not be adopted by designers, so some icons should be killed:

Create an icons.js to manage the Ant Design Vue icon. Take a Loading icon as an example:

/ / @ / src/assets/icons.js export {default as LoadingOutline} from'@ ant-design/icons/lib/outline/LoadingOutline'; copy the code

How do I know which path the icon you want to load is under?

There are three styles of icons under the @ ant-design/icons/lib directory, namely, fill, outline, and twotone. The internal files are not in svg format, but in js and ts format, which is the key to why we can introduce icons in this way.

The next step is to introduce this file by configuring vue.config.js:

/ / vue.config.js module.exports = {configureWebpack: {resolve: {alias: {'@ ant-design/icons/lib/dist$': path.resolve (_ _ dirname,'. / src/assets/icons.js'),} copy the code

Solve Moment multilingual

After solving this, Ant Design Vue is still very large. This is because moment is strongly dependent on this plug-in in Ant Design Vue, so use the webpack plug-in to reduce the package size. Here we only keep the zh-cn language package:

/ / vue.config.js module.exports = {chainWebpack: (config) = > {config .plugin ('ContextReplacementPlugin') .use (webpack.ContextReplacementPlugin, [/ moment [/\] locale$/, / zh-cn/]);},} copy the code

Some components need to be referenced within the page

Some of the larger components in Ant Design Vue, such as DatePicker, should be loaded in the page according to business requirements to ensure the loading speed of the first screen as much as possible:

Import {DatePicker} from 'ant-design-vue'; export default {components: {ADatePicker: DatePicker,},} copy the code

4. Static resources and icons

Static resources

All static resource files are uploaded to Aliyun OSS, so there is a distinction between environment variables.

The VUE_APP_STATIC_URL properties of .env.development and .env.production are configured with the local static resource server address and the online OSS address, respectively.

The local static resource server is created through pm2 + http-server, and the designer can just throw it in after cutting it.

Auto-register Svg icon

In daily development, there are always a large number of icons to use, here we directly choose to use the SVG icon. But wouldn't it be troublesome to find the icon through the path every time you use it?

The following is the solution I want (just name equals the file name):

Copy the code

And finally, after packing, it needs to be merged into a sprite picture.

First of all, you need to automatically register the svg icon under the @ / assets/icons folder, set up webpack and svg-sprite-loader, and package all the files into svg-sprite.

Module.exports = {chainWebpack: (config) = > {config.module .rule ('svg') .addide.add (resolve (' src/assets/icons')) .end () Config.module .rule ('icons') .test (/\ .svg $/) .include.add (resolve (' src/assets/icons')) .end () .use ('svg-sprite-loader') .loader (' svg-sprite-loader');},} copy the code

Write a global Vue component:

/ / @ / components/m-svg/index.js

Const requireAll = (requireContext) = > requireContext.keys () .map (requireContext); const req = require.context ('@ / assets/icons', false, /\ .svg $/); requireAll (req); copy code

@ / components/m-svg/index.vue

Export default {name:'m this.name this.name, props: {name: {type: String, default:''},}, computed: {iconName () {return `# ${this.name}`;},},}; .mw-svg {width: 1.4emm; height: 1.4emm; fill: currentColor; overflow: hidden; line-height: 1em Display: inline-block;} copy the code

Parameter name

Type: String

Default value: null

Description: file name placed under the @ / assets/icons folder

Style

The size of the icon can be changed through the width + height property.

Change by changing the font-size property, width and height = font-zise * 1.4

5. Asynchronous request

Encapsulated Axios

Encapsulate Axios under the @ / libs/request.js path, encapsulating request parameters, request headers, as well as error message, request interceptor, response interceptor, unified error handling, baseURL settings, etc.

Don't talk nonsense and post the code directly:

Import axios from 'axios'; import get from' lodash/get'; import storage from 'store'; / / create axios instance const request = axios.create (default prefix of {/ / API request baseURL: process.env.VUE_APP_BASE_URL, timeout: 10000, / / request timeout}); / / exception interceptor const errorHandler = (error) = > {const status = get (error,' response.status') Switch (status) {/ * eslint-disable no-param-reassign * / case 400: error.message = 'request error'; break; case 401: error.message = 'unauthorized, please login'; break; case 403: error.message = 'access denied'; break; case 404: error.message = `request address error: ${error.response.config.url} `; break; case 408: error.message = 'request timeout'; break Case: error.message = 'server internal error'; break; case 501: error.message = 'service not implemented'; break; case 502: error.message = 'gateway error'; break; case 503: error.message = 'service unavailable'; break; case 504: error.message = 'gateway timeout'; break; case 505: error.message = 'HTTP version is not supported'; break; default: break / * eslint-disabled * /} return Promise.reject (error);}; / / request interceptor request.interceptors.request.use ((config) = > {/ / if token exists / / Let each request carry a custom token, please modify / / eslint-disable-next-line no-param-reassign config.headers.Authorization = `bearer ${storage.get ('ACCESS_TOKEN')} `; return config;}, errorHandler) / / response interceptor request.interceptors.response.use ((response) = > {const dataAxios = response.data; / / this status code is const {code} = dataAxios; / / judged by code (code = undefined) {/ / if there is no code, this is not the interface return dataAxios developed by the backend of the project. / / eslint-disable-next-line no-else-return} else {/ / this is a back-end interface that can be further judged by switch (code) {case 200: / / [example] code = = 200 means there is no error return dataAxios.data Case 'xxx': / / [example] other code return' xxx'; default agreed with backend: / / incorrect code return 'not correct code';}}, errorHandler); export default request; copy code

Distinguish the API address of the online and development environment through VUE_APP_BASE_URL.

Code plays a key role, such as validation when token expires.

A package called sotre is used as a local storage tool to store token.

Cross-domain problem

Generally speaking, cross-domain problems can be solved directly from the backend. If you don't want to disturb them, you can use the proxy proxy provided by devServer:

/ / vue.config.js devServer: {proxy: {'/ api': {target: 'http://47.100.186.132/your-path/api', ws: true, changeOrigin: true, pathRewrite: {' ^ / api':'} copy the code

Mock data

A very common situation, the back-end interface does not come out, the front end is staring at this.

The Mock data function is developed based on mock.js (opens new window) and automatically loads mock configuration files through webpack.

Rules

All mock configuration files should be placed in the @ / mock/services path.

Within @ / mock/services, you can set up business-related folder categories to store configuration files.

All configuration files should be created in accordance with the naming convention of *. Mock.js.

The configuration file uses ES6 Module to export an array of export default or export.

Entry file

Import Mock from 'mockjs'; Mock.setup ({timeout:' 500-800 miles,}); const context = require.context ('. / services', true, /\ .mock.js $/); context.keys () .forEach ((key) = > {Object.keys (context (key)). ForEach ((paramKey) = > {Mock.mock (. Context (key) [paramKey]);}); copy code

Sample template

Import Mock from 'mockjs'; const {Random} = Mock Export default [RegExp ('/ example.*'), 'get', {' range | 50-100 percent: 50, 'data | 10 percent: [{/ / unique ID id:' @ guid ()', / / generate a Chinese name cname:'@ cname ()' / / generate a url url:'@ url ()', / / generate an address county: Mock.mock ('@ county (true)'), / / randomly select a value 'array' from the array. / / randomly generate a time time:'@ datetime ()', / / generate an image image: Random.dataImage ('200x100cycles,' Mock Image'),},],},},] Copy the code

6. Routin

Layout

The layout is temporarily divided into three categories:

FrameIn: BasicLayout-based routing that usually requires login or permission authentication.

FrameOut: routes that do not require dynamic determination of permissions, such as login pages or generic pages.

ErrorPage: for example 404.

Permission verification

By obtaining the permissions of the current user to compare the routing table, the routing table accessible to the current user is generated and dynamically mounted to the router through router.addRoutes.

To determine whether the page needs login status, jump to / user/login if necessary

Jump to / user/login if token does not exist in local storage

If token exists and the user information does not exist, vuex'/ system/user/getInfo' is automatically called.

In routing, the function of permission verification is integrated. When you need to add permissions to the page, add the corresponding key under meta:

Auth

Type: Boolean

Note: when auth is true, this page needs to verify the login permission, which is only valid for frameIn routing.

Permissions

Type: Object

Note: permissions each key corresponds to the verification of permission function. When the value of key is true, it means permission. If key is false, with the v-permission instruction, the corresponding DOM can be hidden.

Post the code for permission verification when the route is redirected:

Import router from'@ / router'; import store from'@ / store'; import storage from 'store'; import util from' @ / libs/utils'; / / progress bar import NProgress from 'nprogress'; import' nprogress/nprogress.css'; const loginRoutePath ='/ user/login'; const defaultRoutePath ='/ home' / * * Route interception * permission verification * / router.beforeEach (async (to, from, next) = > {/ / progress bar NProgress.start () / / verify whether the if of login verification is required in all matches of the current route (to.matched.some ((r) = > r.meta.auth)) {/ / whether there is token as a condition to verify whether or not to log in const token = storage.get ('ACCESS_TOKEN') If (token & & token! = 'undefined') {/ / whether it is on the login page if (to.path = loginRoutePath) {next ({path: defaultRoutePath}) / / query whether to store user information} else if (Object.keys (store.state.system.user.info). Length = 0) {store.dispatch ('system/user/getInfo'). Then (() = > {next ();});} else {next () }} else {/ / jumps to the login interface when not logging in / / carries the full path of the page to be redirected after a successful login ({name: 'Login', query: {redirect: to.fullPath,},}); NProgress.done () }} else {/ / pass next () without identity verification;}}); router.afterEach ((to) = > {/ / progress bar NProgress.done (); util.title (to.meta.title);}); copy code

Page development

According to the business needs, the corresponding page components are created in views according to the routing level, in the form of a folder, and the index.vue file is created in the folder as the entry file of the page.

Components within the page: create a components folder under the page folder, and create corresponding component files within it. If it is a complex component, you should create the component in the form of a folder.

Tool modules: tool modules that can be highly abstract should be created to create js files in @ / src/libs.

7. Construction optimization

Package analysis tool

After building the code, what takes up so much space? Guess intuitively or use webpack-bundle-analyzer.

Const WebpackBundleAnalyzer = require ('webpack-bundle-analyzer'); module.exports = {chainWebpack: (config) = > {if (process.env.use_analyzer) {config. Plugin (' webpack-bundle-analyzer') .use (WebpackBundleAnalyzer.BundleAnalyzerPlugin);},}; copy the code

Turn on Gzip

Yes, in this sentence, the back end has to support your .gz file, and all you have to do is sit and wait for your boss to praise:

ChainWebpack: (config) = > {config .plugin ('CompressionPlugin') .use (CompressionPlugin, []);}, copy the code

Routing lazy loading

This @ vue/cli has been taken care of, but you also need to know how it works and how to configure it.

{path: 'home', name:' Home', component: () = > import (/ * webpackChunkName: "home" * /'@ / views/home/index.vue'),}, copy the code

It is still necessary to add the webpackChunkName comment, at least you know which page has become smelly and big after you pack it.

Preload & Prefetch

It is not clear that these two functions go to @ vue/cli to make up lessons, these two features are very helpful for you to deal with loaded performance.

8. Testing framework

Directly use the official Vue Test Utils, which can test the components, which is very good.

Writing unit tests is actually very difficult to push forward in the team. I don't know what people think.

9. Component library

For many third-party tools, I insist that secondary packaging into vue plug-ins does not have much development cost, but makes you very flexible in subsequent development.

I encapsulated the following libraries with the vue plug-in and submitted them to the npm private server:

Digital animation

Code highlight

Large file upload (slicing, breakpoint continuation, second upload) needs to cooperate with the backend

Picture preview

Excel Import and Export

Rich text editor

Markdown Editor

Code editor

If you are interested in uploading large files, you can leave a message. I will take it out separately and write this piece in detail.

10.Vuex

There are some built-in functions, mainly encapsulating the following functions:

User information management (storing information, operating on token, etc.)

Log in (adjust interface)

Menu management (storing routing information, generating menus, fuzzy queries, etc.)

UA information

Full screen operation

Loading

Log management (message reminder, log retention, log reporting)

11. Filter

Filter is a very useful feature provided by Vue. I heard that vue3 is gone.

{{message | capitalize}} copy the code

I wrote a few commonly used filters:

Date and time

Remaining time

Environment-specific links (mainly for local static resource servers and OSS)

File size

Numerical amount

Floating point precision

twelve。 Instruction

Custom directives can be very helpful:

Component permission verification

Text copy

Shortcut key binding

Scroll to the specified location

Picture lazy load

Focus

13. Development specification

ESLint

Whether it's a multi-person collaboration or an individual project, the code specification is important. This not only greatly avoids basic syntax errors, but also ensures the readability of the code.

Here we use Airbnb JavaScript Style Guide.

This set of norms gives me the impression that it is very rigorous!

CSS specification

Reduce the complexity of selector

The browser reads the selector, following the principle of reading from the right to the left of the selector.

# block .text p {color: red;} copy the code

Find all P elements.

Find out whether the element in result 1 has a parent element named text

Find out whether the element in result 2 has a parent element whose id is block

Selector priority

Inline > ID selector > class selector > tag selector

The shorter the selector, the better.

Try to use high-priority selectors, such as ID and class selectors.

Avoid using the wildcard character *.

Use flexbox

In the early CSS layout, we were able to position elements absolutely, relatively, or floating. Now, we have a new layout method, flexbox, which has an advantage over the early layout, that is, the performance is better. However, there are still some problems with flexbox compatibility, not all browsers support it, so use it with caution. Browser compatibility:

Chrome 29 +

Firefox 28 +

Internet Explorer 11

Opera 17 +

Safari 6.1 + (prefixed with-webkit-)

Android 4.4 +

IOS 7.1 + (prefixed with-webkit-)

Animation performance optimization

In CSS, two property changes, transforms and opacity, do not trigger rearrangement and redrawing; they are attributes that can be handled separately by the composite.

Attribute value

When the value is a decimal between 0 and 1, it is recommended that 0 of the integer part be omitted.

It is recommended that units be omitted when the length is 0.

It is not recommended to use named color values.

It is recommended that when an element needs to hold up its height to contain an internal floating element, it is recommended to clearfix by setting clear on the pseudo class or triggering BFC. Try not to add empty tags.

In addition to common styles, try not to use! important in business code.

It is suggested that the z-index should be layered to manage the visual hierarchy of the absolute positioning elements outside the document stream.

Font typesetting

The font size should not be less than 12px (PC side).

The font-weight property is recommended to be described numerically.

Line-height should use numeric values when defining text paragraphs.

Vue code specification

Routine

When the data property is used in a component (anywhere except new Vue), its value must be the function data () {return {...}} that returns an object.

The definition of prop should be as detailed as possible, or at least its type should be specified.

Attribute of Boolean type, which writes the property value directly when it is true.

Do not manipulate vue variables in computed.

Priority should be given to communication between parent and child components through prop and events rather than this.$parent or changing the prop.

It is always necessary to use key with v-for on components in order to maintain the state of internal components and their subtrees.

V-if and v-for cannot be used at the same time

Public methods should not be attached to prototypes as much as possible. They can be written in utils files or mixin files. Do not register business public components to the global.

Do not mount any third-party plug-ins to the vue prototype.

Highly versatile methods that are encapsulated in libs, global components, or instruction sets.

Sets the scope for the component style.

Try to use instruction abbreviations.

Vuex

State (opens new window) is a single state tree. In state, we need to define arrays, objects, strings, and so on that we need to manage. Only here can we get the state of this object that you define in the components of vue.

Data in state must be modified through mutations.

Each state that may change must synchronously create one or more mutations to change it.

The data obtained by the server is stored in state and retained as the original data, which is immutable.

Getters (opens new window) is a bit like the calculation property of vue.js. When we need to derive some state from the state of store, then we need to use getters,getters to receive state as the first parameter, and the return value of getters will be cached according to its dependency, and will only be recalculated when the dependent value in getters (a value in state that needs to be derived) changes.

Use getters to process the data format you need, not by modifying the state raw data.

MapGetters is not mandatory in components because you may need to use getter and setter.

The only way to change the state is to submit the mutations (opens new window).

The mapMutations helper function is used within the component to map the methods in the component to store.commit calls.

Naming follows the rule of uppercase letters + underscores.

Define CLEAR to ensure that data can be initialized when routing is switched.

Actions

The data interface for page weight is called in actions (opens new window) as much as possible.

The data returned by the server should not be processed as far as possible, and the original data should be retained.

The acquired data must change the state by calling mutations.

Modules

Typically, modules (opens new window) is divided by page.

System is built in by default to ensure the basic function of scaffolding.

Each page module or sub-module of the page adds the attribute namespaced: true.

14. Complete the detailed usage documentation

Tools such as functions or component libraries all need perfect documentation to provide access, and even wheel builders can't resist forgetting many details over a long period of time.

Here I use vuepress to build documents, which is quick and convenient.

15.Git multiplayer collaboration process

The company uses internally built GitLab managed code

Root warehouse

When the project starts, the project manager sets up the most original warehouse, which is called Root warehouse (source warehouse).

The source warehouse has a function:

Summarize the code of each developer involved in the project.

Store code that tends to be stable and distributable.

Submitting a Merge Requests to the Master branch triggers a test environment build (CI/CD).

The source repository is protected and developers cannot develop it directly.

Developer repository

No developer has the permission to operate directly on the Root repository. After the source repository is established, what each developer needs to do is to use a copy of the Fork of the source repository as his or her daily development repository.

Each developer's Fork repository is completely independent and does not interfere with each other.

Each developer submits the code to his or her own warehouse. After the development work is completed, the developer can send Pull Request to the source repository. The local warehouse first merges the source warehouse to resolve the conflict.

Initiate a Merge Request to request the administrator to merge your code into master or other branches in the source repository.

Git process

The front-end project creates dev branches under the Root repository for code pulling and merging, and if there are multiple different test environments, create branches according to the test environment.

Create your dev branch and other functional branches in the local repository.

During the development process, it is not allowed to develop directly on the master branch, create a new branch for development, git checkout-b {branch_name}.

Standard and detailed writing of commit, it is recommended to use git-cz tool for submission.

After completing the development, merge the corresponding branches into the master branch of your own warehouse.

Push the master branch to your own remote repository (Fork repository).

Submit the Merge Requests to the Root warehouse dev branch.

Remind the person in charge of the front end to review the code, resolve conflicts, or put the test environment online.

After conflict resolution, git pull upstream dev pulls the latest code after resolution.

At this point, the study of "what are the technologies implemented by the front-end architecture based on Vue" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report