Skip to content

前端工程化

前端学习攻略

Vue3

https://cn.vuejs.org/guide

js
pnpm create vue

组件化

组件系统是一个抽象的概念;

  • 组件:小型、独立、可复用的单元
  • 组合:通过组件之间的组合、包含关系构建出一个完整应用

SFC

Vue 的单文件组件 (即 *.vue 文件,英文 Single-File Component,简称 SFC) 是一种特殊的文件格式,使我们能够将一个 Vue 组件的模板、逻辑与样式封装在单个文件中.

js
<script setup>
  //编写脚本
</script>

<template>
  //编写页面模板
</template>

<style scoped>
  //编写样式
</style>

Vite

官网:https://cn.vitejs.dev 快速创建前端项目脚手架 配置:https://cn.vitejs.dev/config/

js
pnpm create vite 项目名称
 
npm run dev #启动项目
 
npm run build #构建后 生成 dist 文件夹

创建vite+vue项目

npm create vite@latest my-vue-app -- --template vue

Vue-Router

文档:https://router.vuejs.org/zh/guide/

理解路由

前端系统根据页面路径,跳转到指定组件,展示出指定效果

js
pnpm add vue-router@4 ## 安装路由

main.js引入路由

js

import router from './router'
app.use(router)

管理路由

js

import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/components/Layout.vue'
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      meta: {
        requiresAuth: true
      },
      redirect: '/sell'
    },
    {
      path: '/login',
      component: () => import('@/views/login/Login.vue')
    },
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: 'sell',
          component: () => import('@/views/components/aaa.vue'),
          meta: { requiresAuth: true }
        }, 
      ]
    },
    {
      path: '/:pathMatch(.*)', //动态路由匹配所有未定义路径
      component: () => import('../views/not-found/NotFound.vue')
    }
  ]
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
  const token = localStorage.getItem('token')
  console.log('token', token)
  console.log('requiresAuth', requiresAuth)
  if (requiresAuth && !token) {
    next('/login')
  } else {
    next()
  }
})
// 导航守卫

export default router

Pinia

Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。

https://pinia.vuejs.org/zh/introduction.html

Pinia 三个核心概念:

  • State:表示 Pinia Store 内部保存的数据(data)
  • Getter:可以认为是 Store 里面数据的计算属性(computed)
  • Actions:是暴露修改数据的几种方式。 虽然外部也可以直接读写Pinia Store 中保存的data,但是我们建议使用Actions暴露的方法操作数据更加安全。

安装

js
pnpm install pinia

使用方法

js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import {createPinia} from 'pinia'

const pinia = createPinia();

createApp(App)
    .use(pinia)
    .mount('#app')

setup写法

js
export const useMoneyStore = defineStore('money', () => {
    const salary = ref(1000); // ref() 就是 state 属性
    const dollar = computed(() => salary.value * 0.14); //  computed() 就是 getters
    const eur = computed(() => salary.value * 0.13); // computed() 就是 getters

    //function() 就是 actions
    const pay = () => {
        salary.value -= 100;
    }

    const win = () => {
        salary.value += 1000;
    }

    //重要:返回可用对象
    return {salary,dollar,eur,pay,win}
})

Axios

Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js

https://www.axios-http.cn/docs/intro

js
pnpm install axios

响应

js
 {
  // `data` 由服务器提供的响应
  data: {},
  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,
  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',
  // `headers` 是服务器响应头
  // 所有的 header 名称都是小写,而且可以使用方括号语法访问
  // 例如: `response.headers['content-type']`
  headers: {},
  // `config` 是 `axios` 请求的配置信息
  config: {},
  // `request` 是生成此响应的请求
  // 在node.js中它是最后一个ClientRequest实例 (in redirects),
  // 在浏览器中则是 XMLHttpRequest 实例
  request: {}
}

简单封装

js
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建 axios 实例
const service = axios.create({
  //   baseURL:  'http://222.64.222.247:10003', // 设置你的基础 URL
    baseURL:  '', // 设置你的基础 URL
    timeout: 5000 // 请求超时时间
  })

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    console.log('响应数据:', response)
    // 对响应数据做点什么
    return response.data;
    // if (res.code !== 200) {
    //   // 处理非 200 响应
    //   ElMessage.error(res.message || 'Error')
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  (error) => {
    // 对响应错误做点什么
    console.error('响应错误:', error)
    ElMessage.error('请求失败,请稍后再试')
    return Promise.reject(error)
  }
)

export default service

前端ui库

Ant Design Vue

官网:https://www.antdv.com/

npm create vue@latest

Element Plus

官网:https://element-plus.org/zh-CN/

安装

js
pnpm install element-plus
pnpm install @element-plus/icons-vue #图标

完整引入

js
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'

const app = createApp(App)

app.use(ElementPlus)
app.mount('#app')

图标包

js
// main.ts

// 如果您正在使用CDN引入,请删除下面一行。
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
最近更新