Vue3 路由跳转:详细教程与示例
在 Vue3 中使用路由跳转,需要先安装 vue-router 插件。
- 安装 vue-router 插件
npm install vue-router@4.0.0-beta.13
- 创建 router 实例
在src目录下创建一个router目录,然后创建一个index.js文件,在文件中编写以下代码:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue')
},
{
path: '/about',
name: 'About',
component: () => import('@/views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
上面的代码中,我们定义了两个路由:Home和About,并分别对应了两个组件Home.vue和About.vue。其中,createRouter函数用于创建 router 实例,createWebHistory函数用于创建 HTML5 history 模式的路由,routes定义了所有的路由信息。
- 在 main.js 中使用 router
在main.js文件中,我们需要将 router 实例引入进来,并将其绑定到 Vue 实例上。代码如下:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
- 在组件中使用 router
在组件中,我们可以使用router-link标签来生成路由链接,也可以使用router.push()函数来编程式地跳转路由。例如:
<template>
<div>
<router-link to='/'>Home</router-link>
<router-link to='/about'>About</router-link>
<button @click='gotoHome'>Go to Home</button>
</div>
</template>
<script>
export default {
methods: {
gotoHome() {
this.$router.push('/)
}
}
}
</script>
上面的代码中,我们使用了router-link标签生成了两个路由链接,同时在按钮的点击事件中使用了router.push()函数来跳转到首页。
原文地址: https://www.cveoy.top/t/topic/neIv 著作权归作者所有。请勿转载和采集!