vue3路由的使用

1、引用路由组件

html 复制代码
npm install vue-router

2、创建路由

根据项目结构创建对应的组件(home\news\about)

src 目录下创建 router/index.ts

javascript 复制代码
//引入路由
import { createRouter,createWebHistory,createWebHashHistory } from 'vue-router'
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'


//创建路由器
const router = createRouter({
    history:createWebHistory(),
    routes:[
        {
            path:'/',
            name:'home',
            component:Home
        },
        {
            path:'/news',
            name:'news',
            component:News
        },
        {
            path:'/about',
            name:'about',
            component:About
        }
    ]
})
//导出
export default router

history的两种区别:

1、createWebHistory 浏览器窗口不会显示 # ,但是项目部署到服务器,使用刷新按钮时会出错。

解决:在 nginx.conf里添加:try_files uri uri/ /index.html;

javascript 复制代码
location / {
        root   /usr/share/nginx/html;
	    try_files $uri $uri/ /index.html;
        index  index.html index.htm;
    }

2、createWebHashHistory 浏览器会显示 # ,不美观,但不会出错

3、引入路由

我们要将路由使用到项目中,需要到 main.ts中导入

javascript 复制代码
import {createApp} from 'vue'
import App from './App.vue'
//router目录下只有一个index.ts 则可以省略不写
import router from './router'

//创建一个应用
const app = createApp(App)
//使用路由器
app.use(router)
//挂在整个应用
app.mount('#app')

4、使用路由

在vue文件中使用路由

javascript 复制代码
<template>
    <div class="App">
        <Head/>
        <!--导航区-->
        <div class="navigate">
            <RouterLink to="/" active-class="router-link-active">首页</RouterLink>
            <RouterLink :to="{path:'/news'}">新闻</RouterLink>
            <RouterLink :to="{name:'about'}">关于</RouterLink>
        </div>
        <div class="main-content">
            <RouterView></RouterView>
        </div>
    </div>
</template>

<script lang="ts" setup name="App">
    import {RouterView,RouterLink} from 'vue-router'
    import Head from '@/components/Head.vue'
</script>

<style>
a{
    list-style: none;
    margin-right: 10px;
    text-decoration: none;
    color:gray;
}
.main-content{
    width:500px;
    height:300px;
    border:1px solid grey;
    margin-top: 20px;
}
.router-link-active{
    color:blueviolet;
    font-weight: bold;
}
</style>

RouterLink 路由绑定的两种写法:

1、to="/" 静态绑定

2、:to = "{path:'/home'}" 绑定对象,更加灵活

效果:

相关推荐
铁皮饭盒22 分钟前
成为AI全栈 - 第3课:路由 RESTful Elysia 状态码 设计规范
前端·后端·全栈
顾昂_32 分钟前
Web 性能优化完全指南
前端·面试·性能优化
IT乐手1 小时前
Claude Code + Qwen 的配置方法
javascript·claude
前端程序媛-Tian1 小时前
前端 AI 提效实战:从 0 到 1 打造团队专属 AI 代码评审工具
前端·人工智能·ai
支付宝体验科技1 小时前
Ant Design Pro v6.0.0 发布
前端
T畅N2 小时前
审批流设计器(前端)
前端·elementui·vue·html·流程图·js
AlunYegeer2 小时前
JAVA,以后端的视角理解前端。在全栈的路上迈出第一步。
java·开发语言·前端
IT_陈寒2 小时前
Redis这个内存杀手,差点让我们运维半夜追杀我
前端·人工智能·后端
子兮曰3 小时前
DeepSeek TUI:原生 Rust 打造的终端 AI 编码 Agent
前端·javascript·后端
暗不需求3 小时前
# 深入 React Todos:从零实现一个状态提升与本地持久化的待办应用
javascript·react.js·全栈