一、vue3的路由跳转
1、先安装路由 router.
npm install vue-router
2、路由配置
- 创建router文件夹 并创建index.ts文件
内容如下
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'Home',
component: () => import('../views/home.vue'),
children: [
{
path: 'about',
name: 'about',
component: () => import('../views/about.vue'),
}
]
},
{
path: '/login',
name: 'Login',
component: () => import('../views/login.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
- main.ts文件
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index'
createApp(App).use(router).mount('#app')
- app.vue文件 要配置占位符
<template>
<router-view></router-view>
</template>
3、路由跳转
- 跳转两种写法
1.router-link
在home.vue文件中
<template>
<router-link to="./login">login</router-link>
</template>
2.push
还是在home.vue文件中
<script setup>
import { useRouter } from "vue-router";
const router = useRouter()
const go = () => {
router.push({
name: 'Login'
})
}
</script>
<template>
<button @click="go">跳转</button>
</template>
可以根据name跳转也可以根据path
<script setup>
import { useRouter } from "vue-router";
const router = useRouter()
const go = () => {
router.push('/login')
}
</script>
<template>
<button @click="go">跳转</button>
</template>
或
<script setup>
import { useRouter } from "vue-router";
const router = useRouter()
const go = () => {
router.push({
path: '/login'
})
}
</script>
<template>
<button @click="go">跳转</button>
</template>