Series of articles:

  1. Login and permission control

Vue Responsive Principle Series (hardcore)

  1. The basic principle of
  2. Array handling
  3. Render the watcher

Recently, I finally completed my first Vue project, which is a simple background management system with few business modules, mainly realizing some functions I want to do. During the project, I stepped in a lot of holes, and realized that the front end was deeply malicious to students who changed careers from non-major courses. Therefore, I want to summarize my experience into a few articles, hoping to help students like me.

This first article in this series focuses on the infrastructure of the project (in this case, vue-CLI4.0)

├ ─ ─ public ├ ─ ─ the SRC │ ├ ─ ─ API │ ├ ─ ─ assets │ ├ ─ ─ components │ ├ ─ ─ the config │ ├ ─ ─ the plugins │ ├ ─ ─ the router │ ├ ─ ─ store │ ├ ─ ─ │ ├── views │ ├── app.vue │ ├── main. Js │ ├─ permission. Js │ ├── package.js │ ├─ . The env. Development └ ─ ─. Env. ProductionCopy the code

The overall structure of the project is similar to that of many vUE practical courses. I will explain different parts of the project and many points that beginners are confused about

components

Exercises ├── b-b-Exercises ├── b-b-exercises ├─ b-b-exercises ├─ b-b-exercises ├─ b-b-exercisesCopy the code

Our Components folder may have many modules, files, and can use a single index.js as a unified import entry

export { default as AAAA } from './aaaa'
Copy the code

You don’t need to specify a folder when you import, you just need to

import AAAA from 'src/components'
Copy the code

plugins

│ ├── modules │ ├─ directives │ ├─ directives │ ├─ directives │ ├─ directives │ ├─ directives │ ├─ index.js │ ├─ index.js ├── filters.js │ ├── index.js │ ├── index.js │ ├── index.js │ ├── index.js │ ├── index.js │ ├── index.js │ ├── index.js │ ├── index.jsCopy the code

Plug-in installation

// Take mixins.js as an example
export default function(Vue) {
  Vue.mixin({
    // ...})}// plugins/index.js
import installDirectives from './directives'
import installFilters from './filters'
import installMixins from './mixins'
import registerComponents from './components'

export default {
  install (Vue) {
    installDirectives(Vue)
    installFilters(Vue)
    installMixins(Vue)
    registerComponents(Vue)
  }
}
Copy the code

Automatic registration

Automation is also a part of front-end engineering, so the modules in the plugins of this project are all grouped in an automated way, without manual introduction. When you need to add content, you only need to add it in the registry

Mixins are relatively simple and can only be written in the way shown above

directives & filters

Using filters as an example, the directory structure is as follows

├── filter.js // registry ├─ index.js // registryCopy the code

Filters.js is a filter registry that needs to export an object

const filters = {
  capitalize: function (value) {
    if(! value)return ' '
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)}}export default filters
Copy the code

Index.js is an automated registry

import filters from './filters' // Import the filter registry

export default function (Vue) {
  // Filter the registry object and register the global filter
  Object.keys(filters).forEach(key= > Vue.filter(key, filters[key]))
}
Copy the code

In this way, when you need to add a filter, you only need to add the corresponding method in the registry of filters.js. The registration method of the custom directive is the same as that of the filter

components

The directory structure is as follows

The components ├ ─ ─ modules// The components folder, where the common components are placed└ ─ ─ index. Js/ / register
Copy the code

Automatic registration of global components requires the WebPack require.context API

import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

function installer (Vue) {
  // Get the path of all.vue files in the target folder
  const context = require.context(
    './modules'.true./\.vue$/
  )
  
  context.keys().forEach(filePath= > {
    // Obtain component objects from the file path
    const config = context(filePath)
    let componentName = filePath.replace(/^.*\/+(.*)\.vue/.'$1')
    componentName = upperFirst(camelCase(componentName))
    // Register components globally
    Vue.component(componentName, config.default || config)
  })
}

export default installer
Copy the code

In this way, on the basis of increasing global components only need to add under SRC/plugins/components/modules vue component, and can be nested multiple folders

router

For routing files, you can also use automatic registration of global components, which can divide routing into modules, reduce the amount of code in the routing file, improve the readability of the code, and make it easier to add pages. There is a problem with this, that is, there is an order problem when the menu bar is generated based on the route, but you can add a sort field in the Meta to determine the order of the route in the menu bar, you can choose according to the actual situation.

Many environmental

I believe that many front-end beginners like me, when encountered with this part of the headache, do not know what environment variables mean, next, I will explain why to use environment variables, and how to configure environment variables

Why use environment variables

In simple terms, a project can be divided into two phases: development and launch. Development stage and the on-line stage have different configuration, a simple example, the development phase, for example, we can use the mock to simulated data, so we in the use of axios initiate requests will use the mock interface address, and after the project launch will use the actual interface provided by the company background, so is our project in front of the line, Do you want to change the interface address in your code? This is clearly unrealistic. Therefore, to solve this problem, we can use different environment variables to identify the environment of the project, such as production for production environment, development for development environment, test for test environment, etc. We use environment variables to get the environment of the project, so as to adopt the interface address of the current environment configuration.

Setting environment variables

This script code may be in the scripts field of package.json

"scripts": {
    "dev": "vue-cli-service serve",},Copy the code

When we run this script using NPM run dev, our project will run in the development environment. This is because the script defaults to the development environment, which we can specify by –mode

"scripts": {
    "dev": "vue-cli-service serve --mode development",},Copy the code

Similarly, we can define scripts for other environments

"scripts": {
    "dev": "vue-cli-service serve --mode development"."build": "vue-cli-service build --mode production"
},
Copy the code

Now our project can run in different environments, but how do we get environment variables in the code? The answer is process.env.node_env, and with this API we can get the environment of the project.

Again, we know where the project is, but how do we configure it differently depending on where it is running? Vue-cli provides a way for us to do this by placing an.env file in the project root directory.

├─ public ├─ SRC ├─ package.json ├── vue.config.js ├─.env. Development // Development of the environment for the configuration of ├─.env. Production // Configuration of the Production environmentCopy the code

In.env, we can define environment variables as key=value

NODE_ENV=development
Foo=bar
Copy the code

One thing to note here is that in local development, our code is running in nodeJS environment, so we can use process.env to get the corresponding variable, such as process.env.foo. However, our code actually runs on the user’s browser, and the browser doesn’t have process.env. Vue-cli provides a solution to this problem by prefixing the variable with VUE_APP_ so that we can access it in client code, for example

NODE_ENV=development VUE_APP_BASE_URL=/dev-api VUE_APP_TIMEOUT=1000 VUE_APP_TITLE= development versionCopy the code

Then, we can introduce the corresponding variable in config/index.js

export const BASEURL = process.env.VUE_APP_BASE_URL
export const TIMEOUT = process.env.VUE_APP_TIMEOUT
export const TITLE = process.env.VUE_APP_TITLE
Copy the code

vue.config.jsBasic configuration

Cross-domain configuration

Cross-domain is also a headache for many beginners, and we can use the webpack-dev-server agent to solve cross-domain problems.

devServer: {
  host: 'localhost'.port: 9999.proxy: {
    / / your BASE_URL
    '/api': {
      // Your interface address
      target: 'xxxx'.changeOrigin: true.pathRewrite: {
        '^./api': ' '}}}Copy the code

Set an alias

You can use chainWebpack to set path aliases to improve development efficiency:

chainWebpack: (config) = > {
    config.resolve.alias
      // It can be set according to the actual situation
      .set(The '@', path.resolve(__dirname, 'src'))
      .set('@assets', path.resolve(__dirname, 'src/assets'))
Copy the code