Next.js 入门指南 - 从 Vue 角度的理解

Next.js 入门指南 - 从 Vue 角度的理解

  • [Next.js 入门指南 - 从 Vue 角度的理解](#Next.js 入门指南 - 从 Vue 角度的理解)
    • 整体架构对比
    • 文件结构和路由
      • [Vue 传统方式:](#Vue 传统方式:)
      • [Next.js App Router 方式 (本项目):](#Next.js App Router 方式 (本项目):)
    • 核心概念对比
      • [1. 页面文件 (Vue 的 .vue 文件 → Next.js 的 page.tsx)](#1. 页面文件 (Vue 的 .vue 文件 → Next.js 的 page.tsx))
      • [2. 组件复用](#2. 组件复用)
      • [3. 接口调用 (API Routes)](#3. 接口调用 (API Routes))
      • [4. CSS 和样式](#4. CSS 和样式)
    • 本项目具体文件解读
    • [如何在 Next.js 中调用方法](#如何在 Next.js 中调用方法)
      • [1. 组件内方法调用](#1. 组件内方法调用)
      • [2. 调用 API 方法](#2. 调用 API 方法)
    • [如何使用 CSS](#如何使用 CSS)
      • [1. 使用 Tailwind CSS (本项目使用)](#1. 使用 Tailwind CSS (本项目使用))
      • [2. 在 globals.css 中添加全局样式](#2. 在 globals.css 中添加全局样式)
    • 启动和修改项目

Next.js 入门指南 - 从 Vue 角度的理解

整体架构对比

Vue Next.js
Vue CLI + Vue Router Next.js App Router
src/components & src/views app/ 目录结构
Webpack/Legacy Built-in bundler

文件结构和路由

Vue 传统方式:

复制代码
src/
├── components/
│   ├── Header.vue
│   └── Footer.vue
├── views/
│   ├── Home.vue
│   └── About.vue
└── router/index.js  // 路由配置

Next.js App Router 方式 (本项目):

复制代码
app/
├── layout.tsx       // 应用布局 (类似App.vue)
├── page.tsx         // 首页 (类似Home.vue)
├── globals.css      // 全局样式
└── deepseek-chat/
    ├── layout.tsx   // /deepseek-chat 页面布局
    └── page.tsx     // /deepseek-chat 页面内容

关键区别:没有手动配置路由!

  • Next.js 自动根据文件夹结构生成路由
  • page.tsx 对应路由页面 (相当于 Vue 的 .vue 文件)
  • layout.tsx 是页面布局组件 (类似 Vue 的 <router-view>)

核心概念对比

1. 页面文件 (Vue 的 .vue 文件 → Next.js 的 page.tsx)

Vue 示例 (views/Home.vue):

vue 复制代码
<template>
  <div>
    <h1>{{ title }}</h1>
    <button @click="handleClick">点击</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: '首页'
    }
  },
  methods: {
    handleClick() {
      console.log('按钮被点击')
    }
  }
}
</script>

<style scoped>
h1 { color: blue; }
</style>

Next.js 示例 (app/page.tsx):

tsx 复制代码
import { useState } from 'react';

export default function HomePage() {
  const [title, setTitle] = useState('首页');
  
  const handleClick = () => {
    console.log('按钮被点击');
  };

  return (
    <div>
      <h1>{title}</h1>
      <button onClick={handleClick}>点击</button>
    </div>
  );
}

2. 组件复用

Vue:

vue 复制代码
<!-- components/MyButton.vue -->
<template>
  <button class="my-button"><slot /></button>
</template>

<script>
export default {
  name: 'MyButton'
}
</script>

<style scoped>
.my-button { /* 样式 */ }
</style>

<!-- 在其他页面中使用 -->
<template>
  <MyButton>点击我</MyButton>
</template>

Next.js:

tsx 复制代码
// components/MyButton.tsx
export default function MyButton({ children, onClick }: { children: ReactNode, onClick?: () => void }) {
  return <button className="my-button" onClick={onClick}>{children}</button>;
}

// 在 page.tsx 中使用
import MyButton from './components/MyButton';

export default function Page() {
  return <MyButton onClick={() => console.log('点击')}>点击我</MyButton>;
}

3. 接口调用 (API Routes)

Vue (前端调用外部 API):

javascript 复制代码
// 在 Vue 组件中
methods: {
  async fetchData() {
    const response = await fetch('/api/data'); // 需要后端提供接口
    const data = await response.json();
    this.items = data;
  }
}

Next.js (内置 API Routes):

typescript 复制代码
// app/api/deepseek/route.ts (本项目中的例子)
export async function POST(request) {
  const { messages } = await request.json();
  
  // 处理数据并返回响应
  return new Response(JSON.stringify({ result: 'success' }), {
    headers: { 'Content-Type': 'application/json' }
  });
}

// 在页面中调用
const response = await fetch('/api/deepseek', {
  method: 'POST',
  body: JSON.stringify({ messages })
});

这是 Next.js 强大的地方:直接在项目中定义 API 接口!

4. CSS 和样式

Vue:

vue 复制代码
<template>
  <div class="home-container">
    <h1 class="title">标题</h1>
  </div>
</template>

<style scoped>
.home-container {
  padding: 20px;
}
.title {
  color: blue;
  font-size: 24px;
}
</style>

Next.js:

tsx 复制代码
// 方法1:使用 Tailwind CSS 类名 (本项目使用此方法)
<div className="p-5 bg-blue-100 text-blue-800">
  <h1 className="text-2xl font-bold">标题</h1>
</div>

// 方法2:全局样式在 globals.css 中
// globals.css
.container {
  padding: 20px;
}

// 在组件中导入
import './styles.module.css'; // 或使用 CSS Modules

本项目具体文件解读

主要页面文件:

  • app/page.tsx - 首页 (对应 Vue 的 Home.vue)
  • app/deepseek-chat/page.tsx - 聊天页面 (复杂的聊天界面)

API 接口文件:

  • app/api/deepseek/route.ts - 处理聊天请求的 API (类似 Vuex actions 或后端接口)

样式文件:

  • app/globals.css - 全局样式 (Tailwind CSS + 自定义)

布局文件:

  • app/layout.tsx - 整站布局
  • app/deepseek-chat/layout.tsx - 聊天模块布局

如何在 Next.js 中调用方法

1. 组件内方法调用

tsx 复制代码
export default function ChatComponent() {
  const [messages, setMessages] = useState([]);
  
  // 定义方法
  const addMessage = (message) => {
    setMessages([...messages, message]);
  };
  
  // 调用方法
  const handleSubmit = (e) => {
    e.preventDefault();
    addMessage({text: '新消息', sender: 'user'});
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">发送</button>
    </form>
  );
}

2. 调用 API 方法

tsx 复制代码
const callApi = async () => {
  const response = await fetch('/api/deepseek', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({message: 'hello'})
  });
  const data = await response.json();
  return data;
};

如何使用 CSS

1. 使用 Tailwind CSS (本项目使用)

tsx 复制代码
// 直接在 JSX 中使用类名
<div className="bg-blue-500 text-white p-4 rounded-lg">
  这是一个样式化的 div
</div>

2. 在 globals.css 中添加全局样式

css 复制代码
/* app/globals.css */
.custom-class {
  background-color: #f0f0f0;
  padding: 20px;
}

然后在组件中使用:

tsx 复制代码
<div className="custom-class">内容</div>

启动和修改项目

  1. 启动开发服务器npm run dev
  2. 修改页面内容 :编辑对应的 page.tsx 文件
  3. 修改样式 :修改 globals.css 或直接使用 Tailwind 类名
  4. 添加新页面 :在 app/ 目录下创建新文件夹和 page.tsx

这样就完成了从 Vue 思维到 Next.js 的转换,希望能帮你快速上手 Next.js!

下一篇我们将实战
Next.js 入门指南 - DeepSeek 聊天演示应用

相关推荐
大布布将军2 小时前
⚡️ 深入数据之海:SQL 基础与 ORM 的应用
前端·数据库·经验分享·sql·程序人生·面试·改行学it
川贝枇杷膏cbppg2 小时前
Redis 的 RDB 持久化
前端·redis·bootstrap
D_C_tyu2 小时前
Vue3 + Element Plus | el-table 表格获取排序后的数据
javascript·vue.js·elementui
JIngJaneIL3 小时前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
天外天-亮3 小时前
v-if、v-show、display: none、visibility: hidden区别
前端·javascript·html
jump_jump3 小时前
手写一个 Askama 模板压缩工具
前端·性能优化·rust
Fuly10243 小时前
大模型架构理解与学习
人工智能·语言模型
hellotutu3 小时前
vue2 从 sessionStorage 手动取 token 后,手动加入到 header
vue.js·token·session·header
be or not to be3 小时前
HTML入门系列:从图片到表单,再到音视频的完整实践
前端·html·音视频