引路者👇

前言

一、Vue Router 路由管理

1.1 路由基础

安装 Vue Router

基本配置

1.2 路由参数

定义带参数的路由

在组件中获取路由参数

1.3 路由守卫

全局前置守卫

路由独享守卫

二、Pinia 状态管理

2.1 安装 Pinia

2.2 创建 Pinia Store

2.3 使用 Pinia Store

三、自定义指令

3.1 定义全局自定义指令

3.2 使用自定义指令

3.3 定义局部自定义指令

四、Vue 与其他技术的集成

4.1 Vue 与 Axios

安装 Axios

使用 Axios

4.2 Vue 与 WebSocket

使用 WebSocket

五、Vue 项目优化

5.1 代码分割与懒加载

5.2 静态资源优化

5.3 性能监控

六、Vue 项目部署

6.1 构建项目

6.2 部署到服务器

6.3 使用 CDN

七、Vue 与其他框架的对比

7.1 Vue vs React

7.2 Vue vs Angular

八、总结


前言

        本文旨在提供一个全面而深入的 Vue 进阶指南。本篇Fly将从 Vue Router 的高级用法讲起,逐步深入到 Pinia 状态管理、自定义指令、与其他技术的集成,再到项目优化和部署。

PS : 若想接触基础部分,请移步👇

全网最详细 Vue 项目创建与基础知识指南,一看就会!!!_vue 教程-CSDN博客

一、Vue Router 路由管理

1.1 路由基础

        Vue Router 是 Vue.js 的官方路由管理器,它允许你通过不同的 URL 显示不同的组件,从而实现单页应用(SPA)。

安装 Vue Router

如果在创建项目时未选择引入 Vue Router,可以通过以下命令手动安装:

npm install vue-router@4

基本配置

        在 Vue 项目中,通常会在 src/router/index.js 文件中配置路由。以下是一个简单的路由配置示例:

import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;

main.js 中引入并使用路由:

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.mount('#app');

在组件中使用 <router-link><router-view>

<template>
  <div>
    <h1>首页</h1>
    <router-link to="/about">关于</router-link>
    <router-view></router-view>
  </div>
</template>

1.2 路由参数

路由参数允许你在 URL 中传递动态数据。例如,访问 /user/123,其中 123 是用户 ID。

定义带参数的路由

const routes = [
  {
    path: '/user/:id',
    name: 'User',
    component: User
  }
];

在组件中获取路由参数

<template>
  <div>
    <h1>用户信息</h1>
    <p>用户 ID:{{ userId }}</p>
  </div>
</template>

<script>
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';

export default {
  setup() {
    const route = useRoute();
    const userId = ref(route.params.id);

    watch(() => route.params.id, (newId) => {
      userId.value = newId;
    });

    return {
      userId
    };
  }
};
</script>

1.3 路由守卫

        路由守卫可以用于控制用户访问特定路由的权限。常见的路由守卫包括全局前置守卫、全局后置守卫、路由独享守卫和组件内守卫。

全局前置守卫

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  console.log('全局前置守卫');
  if (to.name === 'About') {
    alert('你即将访问关于页面');
  }
  next();
});

路由独享守卫

const routes = [
  {
    path: '/about',
    name: 'About',
    component: About,
    beforeEnter: (to, from, next) => {
      console.log('路由独享守卫');
      if (to.name === 'About') {
        alert('你正在访问关于页面');
      }
      next();
    }
  }
];

二、Pinia 状态管理

Pinia 是 Vue 3 的官方状态管理库,用于管理应用中的全局状态。

2.1 安装 Pinia

npm install pinia

2.2 创建 Pinia Store

src/stores 目录下创建一个 counter.js 文件:

import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0
    };
  },
  actions: {
    increment() {
      this.count++;
    }
  }
});

2.3 使用 Pinia Store

main.js 中引入并使用 Pinia:

import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';

const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');

在组件中使用 Pinia Store:

<template>
  <div>
    <h1>计数器</h1>
    <p>当前计数:{{ count }}</p>
    <button @click="increment">+1</button>
  </div>
</template>

<script>
import { useCounterStore } from '../stores/counter';

export default {
  setup() {
    const store = useCounterStore();
    return {
      count: store.count,
      increment: store.increment
    };
  }
};
</script>

三、自定义指令

        自定义指令允许你直接操作 DOM 元素,为 Vue 提供更强大的功能。

3.1 定义全局自定义指令

main.js 中定义全局自定义指令:

import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});

app.mount('#app');

3.2 使用自定义指令

<template>
  <div>
    <h1>自定义指令示例</h1>
    <input v-focus placeholder="输入内容">
  </div>
</template>

3.3 定义局部自定义指令

在组件中定义局部自定义指令:

<template>
  <div>
    <h1>局部自定义指令示例</h1>
    <input v-focus placeholder="输入内容">
  </div>
</template>

<script>
export default {
  directives: {
    focus: {
      mounted(el) {
        el.focus();
      }
    }
  }
};
</script>

四、Vue 与其他技术的集成

4.1 Vue 与 Axios

        Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js。它可以方便地发送 HTTP 请求,与后端 API 进行交互。

安装 Axios

npm install axios

使用 Axios

src/api 目录下创建一个 user.js 文件:

import axios from 'axios';

export function getUser(id) {
  return axios.get(`/api/users/${id}`);
}

在组件中使用 Axios:

<template>
  <div>
    <h1>用户信息</h1>
    <p>用户名:{{ user.name }}</p>
    <p>年龄:{{ user.age }}</p>
  </div>
</template>

<script>
import { ref } from 'vue';
import { getUser } from '../api/user';

export default {
  setup() {
    const user = ref({});

    getUser(1).then((response) => {
      user.value = response.data;
    });

    return {
      user
    };
  }
};
</script>

4.2 Vue 与 WebSocket

        WebSocket 提供了在单个 TCP 连接上进行全双工通信的能力。Vue 可以通过 WebSocket 与服务器进行实时通信。

使用 WebSocket

在组件中使用 WebSocket:

<template>
  <div>
    <h1>WebSocket 示例</h1>
    <p>消息:{{ message }}</p>
    <input v-model="newMessage" placeholder="输入消息">
    <button @click="sendMessage">发送</button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const message = ref('');
    const newMessage = ref('');

    const socket = new WebSocket('ws://localhost:8080');
    socket.onmessage = (event) => {
      message.value = event.data;
    };

    const sendMessage = () => {
      socket.send(newMessage.value);
    };

    return {
      message,
      newMessage,
      sendMessage
    };
  }
};
</script>

五、Vue 项目优化

5.1 代码分割与懒加载

代码分割和懒加载可以减少初始加载时间,提高应用性能。Vue Router 支持懒加载路由组件。

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  }
];

5.2 静态资源优化

使用 Webpack 的 file-loaderurl-loader 对静态资源进行优化,将小

图片转换为 Base64 编码,减少 HTTP 请求。

vite.config.js 中配置:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
  build: {
    assetsInlineLimit: 4096 // 小于 4KB 的图片将被转换为 Base64
  }
});

5.3 性能监控

        使用 Vue Devtools 或其他工具监控 Vue 应用的性能,分析渲染时间、内存占用等指标,优化应用性能。

六、Vue 项目部署

6.1 构建项目

在项目根目录下运行以下命令构建项目:

npm run build

构建完成后,项目会在 dist 目录下生成静态文件。

6.2 部署到服务器

dist 目录中的文件上传到服务器的静态资源目录中。如果使用 Nginx 作为服务器,可以在配置文件中添加以下配置:

server {
  listen 80;
  server_name example.com;

  location / {
    root /path/to/dist;
    try_files $uri $uri/ /index.html;
  }
}

6.3 使用 CDN

将静态资源(如图片、CSS、JS 文件)部署到 CDN,提高加载速度。可以在 vite.config.js 中配置 CDN 地址:

export default defineConfig({
  base: 'https://cdn.example.com/'
});

七、Vue 与其他框架的对比

7.1 Vue vs React

特性 Vue React
学习曲线 较低,适合初学者 较高,需掌握 JSX 和组件生命周期
性能 性能优秀,适合中大型项目 性能优秀,适合大型项目
生态系统 生态系统丰富,有 Vue Router、Pinia 等 生态系统丰富,有 React Router、Redux 等
语法 使用模板语法,代码更简洁 使用 JSX,代码更接近 JavaScript

7.2 Vue vs Angular

特性 Vue Angular
学习曲线 较低,适合初学者 较高,需掌握 TypeScript 和 Angular 的复杂概念
性能 性能优秀,适合中大型项目 性能优秀,适合大型项目
生态系统 生态系统丰富 生态系统丰富,但学习成本较高
语法 使用模板语法,代码更简洁 使用 TypeScript,代码更复杂

八、总结

        Vue 3 的发布带来了许多新特性和改进,如 Composition API、Fragment、Teleport 等。

        希望这篇补充博客能够帮助大家更全面地了解 Vue 的进阶知识。在实际开发中,不断实践和探索是提升技能的关键。

        如果操作中遇到其他问题,也可以在评论区留言,Fly帮你在线答疑!!!

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐