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

效果:

相关推荐
XiaoSong19 分钟前
从未有过如此丝滑的React Native开发体验:EAS开发构建完全指南
前端·react.js
掘金者阿豪33 分钟前
打通KingbaseES与MyBatis:一篇详尽的Java数据持久化实践指南
前端·后端
RoyLin1 小时前
TypeScript设计模式:原型模式
前端·后端·node.js
我是天龙_绍1 小时前
vue Composables 组合式函数
前端
zjjuejin1 小时前
Maven项目的核心蓝图:POM文件
前端·maven
小气小憩1 小时前
“暗战”百度搜索页:Monica悬浮球被“围剿”,一场AI Agent与传统巨头的流量攻防战
前端·人工智能
前端付豪1 小时前
1、震惊!99% 前端都没搞懂的 JavaScript 类型细节
前端·javascript·面试
朝与暮1 小时前
js符号(Symbol)
前端·javascript
恋猫de小郭2 小时前
对于普通程序员来说 AI 是什么?AI 究竟用的是什么?
前端·flutter·ai编程
大怪v2 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法