当前位置 : 首页 » 文章分类 :  开发  »  Vue

Vue

Vue 学习笔记

Vue.js 中文官网
https://cn.vuejs.org/

新手向:Vue 2.0 的建议学习顺序 - Vue作者尤雨溪
https://zhuanlan.zhihu.com/p/23134551
https://zhuanlan.zhihu.com/p/23134551

菜鸟教你一步一步读Vue源码 - 510团队
https://510team.github.io/

510团队
https://github.com/510team


第一个 Vue 项目

https://cn.vuejs.org/guide/quick-start.html

1. 安装 Node.js 和 npm

$ npm -v
11.3.0
$ node -v
v24.1.0

2. 使用 create-vue 交互式初始化 Vue 项目

进入想要创建项目的父目录,执行 npm create vue@latest
开始使用 create-vue 交互式初始化 Vue 项目
填入项目名称 vue
特性选择:TypeScript, Router (SPA development), Pinia (state management), ESLint (error prevention), Prettier (code formatting)
执行完后会在目录中创建 vue(项目名)子目录,并在 vue 目录中初始化项目必要文件

> create-vue

┌  Vue.js - The Progressive JavaScript Framework
│
◇  Project name (target directory):
│  vue
│
◇  Select features to include in your project: (↑/↓ to navigate, space to select, a to toggle all, enter to confirm)
│  TypeScript, Router (SPA development), Pinia (state management), ESLint (error prevention), Prettier (code formatting)
│
◇  Select experimental features to include in your project: (↑/↓ to navigate, space to select, a to toggle all, enter to confirm)
│  none
│
◇  Skip all example code and start with a blank Vue project?
│  No

Scaffolding project in /Users/masi/git/my/pyapp/vue...
│
└  Done. Now run:

   cd vue
   npm install
   npm run format
   npm run dev

3. npm install 安装 package.json 依赖

进入 vue (项目名)目录
执行 npm install 会读取当前目录中的 package.json 文件,根据 dependencies 依赖清单安装 npm 依赖到当前目录下的 node_modules 子目录

4. npm run dev 启动 vite 查看页面

进入 vue (项目名)目录
执行 npm run dev 会使用 vite 启动一个本地 server,之后可本地打开 http://localhost:5173/ 查看页面

> vite

  VITE v7.0.6  ready in 661 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  Vue DevTools: Open http://localhost:5173/__devtools__/ as a separate window
  ➜  Vue DevTools: Press Option(⌥)+Shift(⇧)+D in App to toggle the Vue DevTools
  ➜  press h + enter to show help

选项式 API 与 组合式 API


.env 环境配置

Vue 3 通过 .env 文件加载环境变量
在项目根目录创建环境变量文件:

  • .env 全局默认(所有环境共享),
  • .env.development 开发环境
  • .env.production 生产环境
  • .env.staging 预发布环境(可选)

npm run 构建与环境 mode

npm run devvite dev 自动加载 .env + .env.development 环境变量
npm run build 自动加载 .env + .env.production 环境变量
npm run build --mode staging 自动加载 .env + .env.staging 环境变量

仅暴露 VITE_ 开头环境变量

只有以 VITE_ 开头的变量才会暴露给客户端代码(防止敏感信息泄露)

# .env.development
VITE_API_BASE = http://localhost:3000/api
DB_PASSWORD = secret123  # 不会被客户端访问

import.meta.env 组件中访问环境变量

组件中仅可访问 VITE_ 开头的环境变量

// axios 配置示例 (src/utils/request.js)
import axios from 'axios';

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE,
  timeout: 15000,
});

vite.config.js 中访问环境变量

vite.config.js 中可访问所有变量

// vite.config.js 中获取(特殊处理)
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  console.log(env.VITE_API_BASE)
})

mode 当前构建模式 (如 development, production 或自定义模式)
'' 空字符串,特殊参数,表示​​加载所有环境变量​​(包括不带 VITE_ 前缀的变量)


Pinia 状态管理

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

Pinia 是 Vue 3 的​​官方推荐状态管理库​​,替代了 Vuex。它提供更简洁的 API、完整的 TypeScript 支持,并与 Vue DevTools 深度集成。

定义 Store

定义 useCounterStore 的 选项式 API 写法:

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2
  },
  actions: {
    increment() {
      this.count++ // 直接通过 this 访问 state
    }
  }
})

定义 useCounterStore 的 组合式 API 写法:

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const double = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, double, increment }
})

在组件中使用 Store

xxx.vue 中:

<template>
  <!-- 直接从 store 中访问 state -->
  <div>Current Count: {{ counter.count }}</div>
  <p>Double: {{ counter.double }}</p>
  <button @click="counter.increment()">+1</button>
</template>

<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()

// 直接访问属性字段
counter.count++

// 直接修改的话不是响应式的
counter.count = 10

// 通过 actions 方法修改
counter.increment()

// 通过 $patch 方法修改,保持响应式
counter.$patch({ count: counter.count + 1 })

// 重置state,恢复初始状态
counter.$reset()

// 订阅state变化
counter.$subscribe((mutation, state) => {
  console.log('状态变化:', mutation.type, state)
})

// 监听 action 调用
counter.$onAction(({ name, after, args }) => {
  after(() => {
    console.log(`Action ${name} 执行完毕`)
  })
})

</script>

持久化存储

npm install pinia-plugin-persistedstate

// main.ts 中
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

// stores/counter.js 定义中
defineStore('user', {
  state: () => ({ token: '' }),
  persist: true // 自动 localStorage 持久化
})

FontAwesome 图标

FontAwesome 图标搜索

在官方网站搜索图标 https://fontawesome.com/search
搜索筛选 free 免费使用的图标
点击图标查看各种图标接入方式的代码

在 Vue3 中使用 FontAwesome 图标

Set Up with Vue
https://docs.fontawesome.com/web/use-with/vue
Add Icons with Vue
https://docs.fontawesome.com/web/use-with/vue/add-icons

在 Vue3 中使用 FontAwesome 图标的最佳实践是使用 FontAwesome 官方提供的 vue-fontawesome 组件

1、安装 FontAwesome 官方提供的 vue-fontawesome 组件

npm install @fortawesome/vue-fontawesome@latest-3

2、安装 fontawesome-svg-core 核心包

npm install @fortawesome/fontawesome-svg-core

3、安装免费版图标包

npm install @fortawesome/free-solid-svg-icons
npm install @fortawesome/free-regular-svg-icons
npm install @fortawesome/free-brands-svg-icons

4、vue 的 main.ts 中引入 FontAwesome 图标库
可以单个引入使用到的图标,也可以批量引入 fas, fab, far 三个包:

  • 单个引入使用到的图标,按需引入,页面不需要加载用不到的图标,但是每次新增使用都要新加 import 引入很麻烦。
  • 批量引入,后续可以任意使用图标,但会导致页面每次都需要加载全量图标文件,7.0.0 版本的图标大小: fas solid 980kb, fab brands 555kb, far regular 130kb

这里使用批量引入:

// 导入 FontAwesome Vue 组件
import { library } from '@fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

// 批量导入整个图标包(比单个导入图标方便,但包体积较大)
import { fas } from '@fortawesome/free-solid-svg-icons'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { far } from '@fortawesome/free-regular-svg-icons'

// 将整个图标包添加到库中
library.add(fas, fab, far)

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

// 注册 FontAwesome 组件
app.component('font-awesome-icon', FontAwesomeIcon)
app.mount('#app')

5、xxx.vue 的模板 <template> 中使用图标:

<font-awesome-icon icon="fa-solid fa-house" />

问题

font-awesome 图标不展示问题

问题:
在 Python FastAPI + Jinja2 模板 网页中,通过 cdn 引入 font-awesome 7.0.0 图标可正常展示

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.0/css/all.min.css">

但在 Vue3 中,通过 npm 安装 fontawesome 7.0.0 包:

"dependencies": {
  "@fortawesome/fontawesome-free": "^7.0.0"
}

并在 main.ts 中引入:

import '@fortawesome/fontawesome-free/css/all.min.css'

有的图标可显示,有的图标不显示。

原因:
CDN 的 CSS 使用的是 ​​Web Fonts 方案​​(图标作为字体文件)
NPM 包的默认行为是 ​​优先使用更现代的 SVG 渲染​,当缺失 JS 时,SVG 所需 DOM 操作无法执行导致图标不显示。

解决:
在 main.ts 中把 all.js 也引入:

import '@fortawesome/fontawesome-free/css/all.min.css'
import '@fortawesome/fontawesome-free/js/all.js'

Font Awesome 7 的 NPM 包需要 JS 完成 SVG 注入和响应式更新,这是与旧版/CDN 的核心差异。通过引入 JS 文件即可解决动态渲染问题。


上一篇 Java-Servlet

下一篇 HikariCP

阅读
评论
1.9k
阅读预计9分钟
创建日期 2019-05-22
修改日期 2025-08-04
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论