search
HomeWeb Front-endJS TutorialHow to optimize Vue projects
How to optimize Vue projectsJun 08, 2018 am 10:46 AM
vuevue project optimizationoptimization

This time I will show you how to optimize the Vue project and what are the precautions for optimizing the Vue project. The following is a practical case, let's take a look.

The project structure of the Vue class project development is basically similar to the Vue-cli generation method. In this method of development, the most commonly used mode is to enable the agent for mock debugging or remote debugging, that is, using Configure the proxyTable set by Vue-cli or directly use the proxy option provided by Webpack-dev-server. It uses the http-proxy library, so the specific configuration can be viewed:

https://github.com/nodejitsu/node-http-proxy#options

Using these configured parameters we You can make more flexible configurations to achieve better results

Usage requirements

Assume that our local development is currently in the following status:

  • Local development, use local mock Server for data

  • Permission-related interfaces use local mock data, and all others use a designated remote machine

  • The permissions-related interface uses local mock data, and other data sub-interfaces use different remote machines

  • All interfaces use the same remote machine

## Solution

Let’s first look at the classic proxyTable writing method:

proxyTable: {
 '/authui/': {
  target: target,
  changeOrigin: true
 },
 '/vendor/': {
  target: target,
  changeOrigin: true
 }
}
The changeOrigin field is used, mainly Is the header used to change the request. Refining the requirements:

  • Local development: The target can point to a certain port of localhost. As for the verification of the host, it is definitely not necessary.

  • Part of the local machine, and the other fixed remote machine: localhost and remote addresses need to be configured. Most of the remote addresses need to be verified by the host.

  • Same as two, but there are multiple machines: multiple machines need to be manually configured

  • The same remote machine, at this time the machine may need to be strictly verified, That is, the IP must also use the domain name, and the system host can be used only after configuring the system host.

Note: The main difference between strict verification host and ordinary verification host is that during strict verification, the requested URL must be from the remote machine. Domain name,

cannot directly modify the host implementation of the requested header, that is, the domain name must be configured at the system host level.

After analyzing the specific requirements, start preparing the implementation method. The original development method is to execute

npm run dev. If we need to add configuration at the command line level, we need to set it to npm run dev --param=paramvalue. For commands executed using npm's script script, its parameters cannot be obtained through process.env, and are obtained through
process.env.npm_config_paramName , It is not very convenient to use the ready-made command line parameter parsing library, but to save trouble, for the time being, I will use the parsing that comes with npm.

The following parameters are required during the request initiation process:

  • host: The host that needs to be pointed to when initiating the request may not be the same for each machine.

  • port: The port forwarded by the proxy

  • receiver: the remote address used for push, including the ip address. To save trouble, the ip address is not listed separately

Then define the proxy request custom type for configuration:

  • local: local address, that is, localhost

  • remote: The specified remote machine

  • Other custom types: used for other types that have been specified in the configuration file

  • The original version of the request, such as 'http://xxx' or Object type configuration, such proxy will never process

As needed, we add the following parameters to control the proxy Pointing address:

  1. rd: The address of the remote machine

  2. #focus: Strict mode, all custom type proxies are converted to the specified rd machine , only available when the rd parameter exists

  3. allLocal: Custom type proxies all point to the local

  4. host: Request to discover whether to use host, and Not an IP address

To summarize (the serial number points to the previous requirement):

  • Situations where host is required for access: 4

  • 需要更改 host:除 localhost 外都需要更改

  • 需要对已有类型进行转换:1: 需要将所有自定义类型都转换为 local, 2和3:什么也不转换,4:所有的自定义类型全部转换为

remote 类型

这么一看,貌似 host 是不需要的,它的存在主要是针对某些 机器可能需要使用 host 的方式,所以还是保留一下。

实现

逻辑理清了就很简单了,配置文件设置为:

module.export = {
 rd1: {
  host: 'dev1.example.com',
  port: 8838,
  receiver: 'http://1.1.1.1:8888/receiver'
 },
 rd2: {
  host: 'dev2.example.com',
  port: 8838,
  receiver: 'http://1.1.1.1:8888/receiver'
 }
}

proxyTable 配置方式

{
 proxyTable: {
  '/api1': 'remote',
  '/api2': 'rd2',
  '/auth/xx': 'local',
  '/other': 'http://example.com'
 }
}

获取 proxyTable 的代码:

// 处理 proxyTable
const releaseConfig = require('../config/release.conf.js')
const rdConfig = releaseConfig[process.env.npm_config_rd]
const isAllRemote = process.env.npm_config_focus
const useHost = isAllRemote || process.env.npm_config_host
// 是否本机开发,本机开发 remote 会指向 local
const isAllLocal = process.env.npm_config_allLocal
module.exports = function (proxy) {
 const localUrl = `http://localhost:${proxy.localProxyPort}`
 const defaultHost = proxy.defaultRdHost || 'dev-example.com'
 const localProxyPort = proxy.localProxyPort || 8787
 const finalConfig = formatReleaseConfig(releaseConfig)
 const remote = finalConfig.remote || {}
 if (process.env.npm_config_rd) {
  if (!rdConfig) {
   throw new TypeError('RD 机器名称不存在,请在 config/release.conf.js 中进行配置')
  }
  if (!remote.ip) {
   throw new Error('请配置 rd 机器的 receiver')
  }
 }
 if (isAllRemote && !rdConfig) {
  throw new TypeError('focus 只能在提供了 rd 名称后可设置')
 }
 function formatReleaseConfig (config) {
  const result = {}
  Object.keys(config).map((key) => {
   const value = config[key]
   const ipMatch = (value.receiver || '').match(/:\/\/(.*?):\d/)
   const ip = ipMatch && ipMatch[1]
   result[key] = {
    ip,
    host: value.host || defaultHost,
    port: value.port || '8391'
   }
  })
  // 设置 remote
  if (rdConfig) {
   const ipMatch = (rdConfig.receiver || '').match(/:\/\/(.*?):\d/)
   const ip = ipMatch && ipMatch[1]
   result.remote = {
    ip,
    host: rdConfig.host || defaultHost,
    port: rdConfig.port || '8391'
   }
  }
  // 设置 local
  result.local = {
   ip: 'localhost',
   host: 'localhost',
   port: localProxyPort
  }
  return result
 }
 function setProxy (proxyTable) {
  const result = {}
  Object.keys(proxyTable).forEach((api) => {
   let type = proxyTable[api]
   const isCustomType = typeof type === 'string' && !/^http/.test(type)
   if (isCustomType && type !== 'remote' && type !== 'local' && !finalConfig[type]) {
    throw new TypeError(`代理类型${type}不正确,请提供 http 或 https 类型的接口,或者指定正确的 release 机器名称`)
   }
   if (type === 'remote' && !finalConfig.remote) {
    type = 'local'
   }
   if (isCustomType) {
    if (isAllRemote && type !== 'remote') {
     type = 'remote'
    }
    if (isAllLocal && type !== 'local') {
     type = 'local'
    }
   }
   const targetConfig = finalConfig[type]
   let target = type
   if (targetConfig) {
    target = {
     target: `http://${useHost ? targetConfig.host : targetConfig.ip}:${targetConfig.port}`,
     // 使用 host 时需要转换,其他不需要转换
     headers: {
      host: `${targetConfig.host}:${targetConfig.port}`
     }
    }
   }
   result[api] = target
  })
  return result
 }
 return {
  proxyTable: setProxy(proxy.proxyTable),
  host: remote.host || defaultHost
 }
}

用法

用法中需要配置两种指向:系统 host 和浏览器代理 Host。
之所以要两种 host, 本质上是因为接口使用的域名
和我们的本地访问的域名是相同的,同一域名无法指向两个地址,所以相当于对浏览器端进行了拦截。
系统 host 推荐使用 switchHost 进行切换,浏览器推荐使用 whistle 进行切换。

本地开发

host 配置:无
whistle 配置:默认的域名

127.0.0.1 dev.example.com

启动命令:

npm run dev
npm run dev --allLocal

注: 此时 proxyTable 中配置的 remote 全部转换为 local,在 allLocal 参数时将所有自定义类型转换为 local

本地 + 1 台远程

host 配置:无
whistle 配置:默认的域名
127.0.0.1 dev1.example.com
127.0.0.1 dev2.example.com

启动命令:

npm run dev --rd=rd1
npm run dev --rd=rd1 --host

注: --host 表示使用访问使用 host 而非 ip,使用时需要 host 地址

本地 + n 台远程

host 配置:无

whistle 配置:默认的域名

127.0.0.1 dev1.example.com

127.0.0.1 dev2.example.com

{
 proxyTable: {
  '/api1': 'rd1',
  '/api2': 'rd2',
  '/auth/xx': 'local',
  '/other': 'http://example.com'
 }
}

proxyTable 配置:

启动命令:

npm run dev

远程 1 台机器

host 配置:

1.1.1.1 dev1.example.com
1.1.1.1 dev2.example.com

whistle 配置:默认的域名

127.0.0.1 dev1.example.com
127.0.0.1 dev2.example.com

启动命令:

npm run dev --rd=rd1 --focus

组件优化

vue 的组件化深受大家喜爱,到底组件拆到什么程度算是合理,还要因项目大小而异,小型项目可以简单几个组件搞定,甚至不用 vuex,axios 等等,如果规模较大就要细分组件,越细越好,包括布局的封装,按钮,表单,提示框,轮播等,推荐看下 Element 组件库的代码,没时间写这么详细可以直接用 Element 库,分几点进行优化

•组件有明确含义,只处理类似的业务。复用性越高越好,配置性越强越好。

•自己封装组件还是遵循配置 props 细化的规则。

•组件分类,我习惯性的按照三类划分,page、page-item 和 layout,page 是路由控制的部分,page-item 属于 page 里各个布局块如 banner、side 等等,layout 里放置多个页面至少出现两次的组件,如 icon, scrollTop 等

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

redux-thunk实战项目案例详解

如何使用Angular数据绑定机制

The above is the detailed content of How to optimize Vue projects. 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
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

VSCode插件分享:一个实时预览Vue/React组件的插件VSCode插件分享:一个实时预览Vue/React组件的插件Mar 17, 2022 pm 08:07 PM

在VSCode中开发Vue/React组件时,怎么实时预览组件?本篇文章就给大家分享一个VSCode 中实时预览Vue/React组件的插件,希望对大家有所帮助!

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 Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.