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'}" 绑定对象,更加灵活

效果:

相关推荐
IT_陈寒2 小时前
Python开发者必知的5大性能陷阱:90%的人都踩过的坑!
前端·人工智能·后端
codingWhat3 小时前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js
Lee川3 小时前
深度拆解:基于面向对象思维的“就地编辑”组件全模块解析
javascript·架构
代码老中医3 小时前
2026年CSS彻底疯了:这6个新特性让我删掉了三分之一JS代码
前端
进击的尘埃3 小时前
Web Worker 与 OffscreenCanvas:把主线程从重活里解放出来
javascript
不会敲代码13 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
踩着两条虫3 小时前
VTJ.PRO 双向代码转换原理揭秘
前端·vue.js·人工智能
扉川川3 小时前
OpenClaw 架构解析:一个生产级 AI Agent 是如何设计的
前端·人工智能
远山枫谷3 小时前
一文理清页面/组件通信与 Store 全局状态管理
前端·微信小程序
codingWhat3 小时前
手撸一个「能打」的 React Table 组件
前端·javascript·react.js