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

效果:

相关推荐
猫猫不是喵喵.2 分钟前
Vue3 中 computed 计算属性与 watch、watchEffect 监听
前端·javascript·vue.js
En^_^Joy14 分钟前
Vue项目创建与入口配置全攻略
前端·vue.js·arcgis
爱码小白36 分钟前
importlib模块
开发语言·前端·python
猫猫不是喵喵.1 小时前
Vue2 的 Vuex 状态管理与 Vue3 的 Pinia 状态管理
前端·javascript·vue.js
greenbbLV1 小时前
中小公司积分商城选型:SaaS与私有化方案对比解析
大数据·前端·小程序
看昭奚恤哭2 小时前
Flutter 布局核心思想
开发语言·javascript·flutter
朝阳5812 小时前
Cesium `Camera.flyTo`:“飞过去“
javascript
NutShell Wang3 小时前
Vite 8.1 深度拆解:Rolldown 统一打包器如何终结前端构建的「双引擎时代」
前端·rust·开源·vite·开发者工具·vibe coding
朱容zr3331333 小时前
请解释“回表”的概念。
java·前端·数据库
leslie1183 小时前
webpack笔记
前端·webpack