vue3实现页面跳转

有需求是在vue项目中实现点击按钮完成页面跳转。这里不适用a标签,而是用vue自带的vue-router。

首先看一下项目结构

src

│ App.vue

│ main.js

├─router

│ index.js

└─views

index.vue

content.vue

可以看到,我在初始的vue项目中添加了一个文件夹router,并在里面添加了一个index.js文件。而view文件夹则是存放需要跳转的页面,里面分别是代表首页的index.vue文件和内容页面content.vue,接下来看看5个文件各自有什么内容。

App.vue文件

html 复制代码
<script setup>
</script>

<template>
    <router-view></router-view>
</template>

<style scoped>

</style>

很简单,只是加了用于显示路由页面内容的<router-view></router-view>

main.js文件

html 复制代码
import {createApp} from 'vue'
import App from './App.vue'
import router from "@/router/index.js"  // 导入路由

// 注册路由
const app = createApp(App)
app.use(router)
app.mount("#app")

这个文件中我引入了router文件夹中的index.js文件,并且使用了其中的router,那么下面来看看这个index.js文件的内容。

router/index.js文件

html 复制代码
import {createRouter, createWebHistory} from "vue-router";


// 路由配置
const routes = [
    {
        //斜杠重定向到首页
        path: "/",
        redirect: "/index",
    },
    {
        //首页
        path: "/index",
        name: "index",
        component: () => import('@/views/index.vue')
    },
    {
        //内容页
        path: "/content",
        name: "content",
        component: () => import('@/views/content.vue')
    },
   
]

// 路由对象
const router = createRouter({
    history: createWebHistory(),
    routes: routes,
})

export default router   // 导出供其他组件导入

在这个文件中我定义了一个路由配置和一个路由对象,并为其配置路由配置,最后导出该组件。

view/index.vue文件

html 复制代码
<template>
<div class="container">
  <li><router-link to="/">首页</router-link></li>
  <li><router-link to="/content">内容页面</router-link></li>
</div>
</template>

这里我们用router-link来作为跳转的按钮(当然可以在外面再套一个button添加样式)

view/content.vue文件

html 复制代码
<template>
<div class="container">
  <li><router-link to="/">首页</router-link></li>
  <li><router-link to="/content">内容页面</router-link></li>
</div>
</template>

这里我们用router-link来作为跳转的按钮(当然可以在外面再套一个button添加样式),和首页一样,这样点击后就可以实现跳转了

相关推荐
悠哉摸鱼大王3 分钟前
cesium学习(二)-地图地形
前端·cesium
青山师22 分钟前
【AI热点资讯】5月10日AI热点:Cloudflare裁员1100人、Musk庭审第二周回顾、OpenAI发布Codex Chrome插件
前端·人工智能·chrome·ai·ai热点
TA远方44 分钟前
【JavaScript】Promise对象使用方式研究和理解
javascript·编程·脚本·web·js·promise·委托
阿赛工作室1 小时前
AI时代WEB开发人员生存与发展报告
前端·人工智能·node.js
用户125758524361 小时前
写了三年定时任务还在手改 Cron 表达式?这个 GoFrame 后台框架帮你全闭环了
vue.js
ZC跨境爬虫1 小时前
跟着 MDN 学 HTML day_36:(深入理解 Comment 接口与 DOM 注释节点)
前端·javascript·ui·html·音视频·视频编解码
石小石Orz2 小时前
Harness Engineering 到底是什么?概念、实战与争议,一次全部讲清楚
前端·后端
悠哉摸鱼大王2 小时前
cesium学习(三)-3d tiles
前端·cesium
前端那点事2 小时前
Vue3自定义Hooks保姆级教程!从原理到企业级实战,告别混乱代码
前端·vue.js
前端那点事2 小时前
别再乱用Vue3响应式!ref、reactive、toRef、toRefs完整区别+企业级落地实战
前端·vue.js