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添加样式),和首页一样,这样点击后就可以实现跳转了

相关推荐
孤水寒月2 小时前
基于HTML的悬窗可拖动记事本
前端·css·html
祝余呀2 小时前
html初学者第一天
前端·html
脑袋大大的3 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
速易达网络4 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码
耶啵奶膘4 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
JoJo_Way4 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
视频砖家5 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能
lyj1689975 小时前
vue-i18n+vscode+vue 多语言使用
前端·vue.js·vscode
小白变怪兽6 小时前
一、react18+项目初始化(vite)
前端·react.js
ai小鬼头7 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github