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

效果:

相关推荐
岳哥i19 小时前
vue鼠标单机复制文本
javascript
jacGJ20 小时前
记录学习--文件读写
java·前端·学习
毕设源码-赖学姐20 小时前
【开题答辩全过程】以 基于WEB的实验室开放式管理系统的设计与实现为例,包含答辩的问题和答案
前端
幻云201020 小时前
Python深度学习:从筑基到登仙
前端·javascript·vue.js·人工智能·python
我即将远走丶或许也能高飞1 天前
vuex 和 pinia 的学习使用
开发语言·前端·javascript
钟离墨笺1 天前
Go语言--2go基础-->基本数据类型
开发语言·前端·后端·golang
爱吃泡芙的小白白1 天前
Vue 3 核心原理与实战:从响应式到企业级应用
前端·javascript·vue.js
卓怡学长1 天前
m115乐购游戏商城系统
java·前端·数据库·spring boot·spring·游戏
码上成长1 天前
JavaScript 数组合并性能优化:扩展运算符 vs concat vs 循环 push
开发语言·javascript·ecmascript
老陈聊架构1 天前
『AI辅助Skill』掌握三大AI设计Skill:前端独立完成产品设计全流程
前端·人工智能·claude·skill