专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

Vue3全新的前端构建工具vite学习 基于vue的前端架构设计

ins518 2024-10-07 13:25:36 技术文章 9 ℃ 0 评论

一、Vite介绍

1.1 vite是什么?

Vite (法语 "快速的",发音 /vit/) 是一种新型前端构建工具

1.2特点

vite是一个开发构建工具,

开发过程中它利用浏览器native ES Module特性导入组织代码,

生产中利用rollup作为打包工具。

它有如下特点:

  • 光速启动
  • 热模块替换
  • 按需编译

1.3浏览器的支持



1.3.1 使用插件进行兼容

@vitejs/plugin-legacy

Note: this plugin requires vite@^2.0.0-beta.12.

1.3.2 安装依赖

npm install @vitejs/plugin-legacy -D

1.3.3 配置

import legacy from '@vitejs/plugin-legacy'
export default {
	plugins: [
		legacy({
			targets: ['defaults', 'not IE 11']
		})
	]
}

1.3.4 注意

按照上面的配置会导致打包element相关的icon路径,在根目录的二级文件夹的路径出错,即base的配置会出错,具体原因有待研究。

实际操作中发现装了出问题了(有待研究)。


二、使用Vite2项目

提示:为了快速编码,可以在vscode中安装vue vscode snippet

2.1 Node.js运行版本

Vite 需要 Node.js 版本 >= 12.0.0

2.2 执行命令行

node -v
npm -v

# npm 6.x
npm init @vitejs/app my-vue-vite --template vue

# npm 7.x, 需要额外的双横线
npm init @vitejs/app my-vue-vite -- --template vue
cd my-vue-vite
npm install
npm run dev


三、Vite2配置变化

3.1 网站地址

http://vitejs.dev/config

3.2 哪些变化

  • 配置选项: vue特有选项、创建选项、css选项, jsx选项等
  • 别名行为: 不再要求/开头或结尾
  • 浏览器vue支持:通过@vitejs/plugin-vue插件支持
  • React支持
  • HMR API变化
  • 清单格式变化
  • 插件API重新设计


注意: 通过现在的文档发现,别名的重写现在推荐使用插件的形式引入

https://github.com/rollup/plugins/tree/master/packages/alias#entries

npm install @rollup/plugin-alias --save-dev
import alias from '@rollup/plugin-alias'

module.exports = {
      input: 'src/index.js',
      output: {
          dir: 'output',
          format: 'cjs'
      },
      plugins: [
        alias({
          entries: [
              { find: 'utils', replacement: '../../../utils' },
              { find: 'batman-1.0.0', replacement: './joker-1.5.0' }
          ]
     	 })
		]
}

通过运行代码可以发现另一种写法

resolve:{
		alias: {
			"@":  path.resolve(__dirname, "src")
		}
},


四、Vue3 setup script详解


五、安装vue-router4和vuex4

5.1 安装依赖

npm  install  vue-router@next  vuex@next  --save-dev

5.2 配置

main.js

import router from './router'
import store from './store'
createApp(App).use(router).use(store).mount('#app')

router/index.js

import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
        history: createWebHashHistory(),
        routes: [
            {
                  path: '/',
                  name: 'home',
                  component: ()=> import('@/views/home.vue')
            }
    		]
})

export default router

store/index.js

import { createStore } from 'vuex'

export default createStore({
    state: {
    		counter: 0,
    } ,
    mutations: {
        add(state){
        		state.counter++
        }
    }
})

5.3使用

<div @click="$store.commit('add')">vuex: {{$store.state.counter}}</div>


六、样式管理

6.1 安装依赖

npm install sass -D

6.2 配置

styles

styles/index.scss

@import './variables.scss';
@import './mixin.scss';
@import './transition.scss';
@import './global.scss';
@import './element-ui.scss';
@import './sidebar.scss';

main.js

// 全局样式
import './styles/index.scss'


七、整合element3

7.1 安装依赖

npm i element3 -S

7.2 配置

plugin/element3.js

1、全局引入

// 全局引入element3
import element3 from 'element3'
import 'element3/lib/theme-chalk/index.css'

export default (app)=> {
		app.use(element3)
}

2、局部引入

// 按需加载

import { ElButton, ElInput } from 'element3'
import 'element3/lib/theme-chalk/button.css'
import 'element3/lib/theme-chalk/input.css'

export default (app)=> {
		app.use(ElButton).use(ElInput)
}

八、基础布局


九、动态导航侧边栏


十、动态导航面包屑

<template>
      <el-breadcrumb class="app-breadcrumb" separator="/">
            <transition-group name="breadcrumb">
                  <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
                        <span
                        v-if="item.redirect === 'noRedirect' || index == levelList.length"
                        class="no-redirect"
                        >{{ item.meta.title }}
                         </span>
                        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
                  </el-breadcrumb-item>
            </transition-group>
      </el-breadcrumb>
</template>

<script setup>
import { compile } from 'path-to-regexp'
import { reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const levelList = ref(null)
const router = useRouter()
const route = useRoute()
const getBreadcrumb = () => {
// 留下只有title的路由
let matched = route.matched.filter((item)=> item.meta && item.meta.title)
// 首页判断
const first = matched[0];
if(first.path!=='/'){
    matched = [{
        path: '/home',
        meta: {
            title: '首页'
        }
    }].concat(matched)
}

// 拼出最终需要展现的跳转数据
levelList.value = matched.filter((item)=>item.meta && item.meta.title && item.meta.breadcrumb!==false)
}

// 手动解析path中可能存在的参数
const pathCompile = (path) => {
    var toPath = compile(path)
    return toPath(route.params)
}

const handleLink = (item) => {
    const { redirect, path } = item;
    if(redirect){
        router.push(redirect)
        return
		}
		router.push(pathCompile(path))
}

// 首次调用
getBreadcrumb()

// 监控route变化
watch(route, getBreadcrumb)
</script>

<style lang="scss" scoped>
.app-breadcrumb
  .el-breadcrumb{
      display: inline-block;
      font-size: 14px;
      line-height: 50px;
      margin-left: 8px;
  }
}
</style>


十一、配置网络请求

11.1 安装依赖

npm i axios -S

11.2 添加配置文件

.env.development

VITE_BASE_API=/api

.env.production

VITE_BASE_API=/

11.3 请求封装

utils/request.js

import axios from 'axios'
const baseURL = import.meta.env.VITE_BASE_API
const service = axios.create({
        baseURL,
        timeout: 5000 // request timeout
});

// 发起请求之前的拦截器
service.interceptors.request.use(config => {
		// 如果有token 就携带tokon
		const token = window.localStorage.getItem('authorization')
    if (token) {
        config.headers.common.Authorization = token
    }
		return config
	},
	error => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(response => {
      const res = response.data
      if (response.status !== 200) {
     			 return Promise.reject(new Error(res.message || 'Error'))
      } else {
      		return res
      }
 },  error => {
      return Promise.reject(error)
})

export default service


十二、使用eslint

npm install --save-dev @typescript-eslint/eslint-plugin @vue/eslint-config-standard @vue/eslint-config-typescript eslint eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-vue

新建.eslintrc.js

"scripts": {
			"lint": "eslint --fix src/**/*.{js,ts,tsx,vue}"
},

如何做兼容,这里大家可以做个思考

十三、项目打包

13.1 执行命令

npm run build

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表