How to build a strong vue3 project

As we all know, vue is a framework that does not have strong background support and takes off purely by users.
Now vue is a hot batch, and when many excellent frameworks are mature, it just supports half of the front-end sky.
Well, vue updates are changing with each passing day, a good project system is even more powerful for development and maintenance, and post-maintenance should not be too cool, so how to build a robust vue3 project?

github address: https://github.com/zhengyimeng/vue-model

↑ I hope you can read the project directly, read the content after reading it, and not just comment, because my article is not complete 

First of all, we basically use @vue/cli to build projects now, and execute vue create my-app


Create ok, need to consider

1. Writing css styles - Generally speaking, .css is uncomfortable to write
2. router router system - a necessary system for single page applications
3. store public storage system - public data storage, throttling can also be used in any component
4. request background interaction system——ajax || fetch || axios encapsulation
5. language language system——language switching, internationalization
6. utils public method——a utility, which is the manual work interspersed in the project
7. config public Configuration - some constants

Ok, after knowing this, we can start to create, using the project created by @vue/cli just now as a template


1. css

Let's add stylus-loader (currently the best style processor) processor to write styles

yarn add -D stylus stylus-loader@^3
// Note here that the built-in stylus-loader used by @vue/cli is version 3.xx, higher versions may report errors

Because we need to use stylus variables later, we create a variables.styl file in the my-app/src directory to put some initial css variables and methods.

variables.styl

// Color
$brand-color = #409EFF
$success-color = #67C23A
$warning-color = #E6A23C
$danger-color = #F56C6C
$info-color = #909399

// Font Color
$font-main = #303133
$font-plain = #606266
$font-second = #909399
$placeholder = #C0C4CC

// Border Color
$border-1 = #DCDFE6
$border-2 = #E4E7ED
$border-3 = #EBEEF5
$border-4 = #F2F6FC

// Base Color
$black = #000000
$white = #ffffff

// Border Style
$small-border-radius = 2px
$big-border-radius = 4px

// Box Shadow
$base-box-shadow = 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
$tint-box-shaodw = 0 2px 12px 0 rgba(0, 0, 0, 0.1)

// Dialog Style
$dialog(width = 400, height = 400)
  _width = unit(width, px)
  _height = unit(height, px)
  width _width
  height _height
  box-shadow $base-box-shadow

These are the ones I usually use, and I can add them according to the variables I need. Since we need to use these variables globally, we need to configure vue.config.js

We add the file vue.config.js in the root directory of my-app

view.config.js

const path = require('path')

module.exports = {
  publicPath: '/',
  css: {
    loaderOptions: {
      stylus: {
        import: [path.join(__dirname, 'src/variables.styl')]
      }
    }
  }
}

In this way, even if the configuration of stylus is completed, the method of use is very simple, in the .vue file

<style lang="stylus" scoped>
  .message
    color $success-color

  .dialog
    $dialog()
</style>

2. router

The router is relatively simple, and you can do it without thinking about the vue-router document

Let's download vue-rotuer first

yarn add vue-router

Create router/index.js in the my-app/src directory 

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Login from '@/views/login/index.vue'
import { getRoutes } from './routes'

const systemRoutes = getRoutes()

// 公共路由(不需要登录)
export const adminRoutes = [
  {
    path: '/login',
    name: 'Login',
    meta: { title: 'Login' },
    component: Login
  }
]

// 默认 route
const routes = [
  ...adminRoutes,
  ...systemRoutes,
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    meta: { title: '404' },
    component: () => import('../views/error-page/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export function setRoutes(routes) {
  routes.forEach(route => router.addRoute(route))
}

export default router

As you can see above, my router is generally saved separately, which is easy to maintain. We create routes.js under the router folder

routes.js

import { RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'

// 管理页面路由
const manageRoutes = [
  {
    path: '/home',
    name: 'Home',
    component: Layout,
    meta: { title: 'Home', icon: 'home' },
    children: [
      { path: '', component: () => import('../views/home/manage.vue') }
    ]
  },
  // ...
]

// 其他路由
const otherRoutes = [
  {
    path: '/home',
    name: 'Home',
    component: Layout,
    meta: { title: 'Home', icon: 'home' },
    children: [
      { path: '', component: () => import('../views/home/other.vue') }
    ]
  }
]

// 其他路由2
const otherRoutes2 = [
  {
    path: '/home',
    name: 'Home',
    component: Layout,
    meta: { title: 'Home', icon: 'home' },
    children: [
      { path: '', component: () => import('../views/home/wallet-admin.vue') }
    ]
  }
]

export function getRoutes(type) {

  // 添加路由
  if (type === 'manage') {
    return manageRoutes
  } else if (type === 'other') {
    return otherRoutes
  } else if (type === 'other2') {
    return otherRoutes2
  }

  return []
}

It is also very simple to use, just use app.use(router) in main.js 


3. store

Will anyone read this long article? Why don't you try how to create it yourself, the store is relatively simple, so I won't explain it


4. request

Create utils/request.js, just paste my code

import axios from 'axios'
import { ElMessage } from 'element-plus'
import { logout } from './auth'

const request = axios.create({
  baseURL: process.env.BASE_URL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

request.interceptors.request.use(
  function(config) {
    config.headers['Accept-Language'] = localStorage.getItem('lang') || 'en'
    return config
  },
  function(error) {
    const result = error.request?.data
    ElMessage.error(result?.msg || error.message)
    return Promise.reject(result || error)
  }
)

request.interceptors.response.use(
  function(response) {
    //console.log(response)
    return response.data
  },
  function(error) {
    const result = error.response?.data
    ElMessage.error(result?.msg || error.message)
    if (error.response?.status === 403) {
      logout()
    }
    return Promise.reject(result || error)
  }
)

export default request

What other things can't?


I was too lazy to update when I came here, but some people said that the writing is good, which means that someone is reading it, so I will attach a project address. Of course, this project is an empty shell, but it has all internal organs. It should be able to solve everyone's project construction needs.


github address: https://github.com/zhengyimeng/vue-model

Guess you like

Origin blog.csdn.net/weixin_42335036/article/details/118354494