Vue3中路由的相关配置
1、路由的配置
在src路径下新建router文件夹,然后在该文件夹新建index.js文件
安装vue-router
cnpm i vue-router@next --save
index.js文件配置如下。
import { createRouter, createWebHistory } from "vue-router";
const addCount = () => import('../components/addCount.vue')
const Father = () => import('../components/father.vue')
const routes = [
{
path: "/",
redirect: '/add'
},
{
path: "/father",
component: Father,
},
{
path: "/add",
component: addCount
},
]
const router = createRouter({
history: createWebHistory(),
routes: routes
})
export default router
然后配置main.js 引入router
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
//使用router
//引入elementPlus
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
//引入router
import router from './router/index'
const app = createApp(App)
//使用ElementPlus
app.use(ElementPlus)
//使用router
app.use(router)
app.mount('#app')
2、路由的跳转
方式一
引入useRouter
<template>
<div>
<el-button type="primary" @click="changeRouter"> 跳转路由 </el-button>
</div>
</template>
<script>
import { useRouter} from 'vue-router'
export default {
setup() {
const router = useRouter()
const changeRouter = () => {
router.push('/father')
}
return { changeRouter }
}
}
</script>
<style scoped>
</style>
方式二router-link
<router-link to="/child">子页面</router-link>
方式三
<template>
<div>
<el-button type="primary" @click="toAdd">下一页</el-button>
</div>
</template>
<script>
import router from '../router/index.js'
export default {
methods: {
toAdd() {
router.push('/add')
},
},
}
</script>
<style scoped>
</style>
3、路由的传参
引入useRoute
<template>
<div>
<el-button type="primary" @click="changeRouter"> 跳转路由 </el-button>
</div>
</template>
<script>
import { useRouter, useRoute } from 'vue-router'
export default {
setup() {
const router = useRouter()
const route = useRoute()
const changeRouter = () => {
router.push({
path: '/father',
//传递的参数
query: {
name: 'zz',
},
})
}
return { changeRouter }
},
}
</script>
<style scoped>
</style>
如下图:father页面就可以通过route.query.name获取到"zz"
4、路由的嵌套
通过router-view和子路由的方式嵌套
router/index.js
import { createRouter, createWebHistory } from "vue-router";
const Father = () => import('../components/father.vue')
const children = () => import('../components/child.vue')
const routes = [
{
path: "/",
redirect: '/father'
},
{
path: "/father",
component: Father,
children:
[
{
path: '/child',
component: children
}
]
},
]
const router = createRouter({
history: createWebHistory(),
routes: routes
})
export default router
father.vue
<template>
<div>
<h1 class="h">我是爷爷</h1>
<br />
<router-link to="/child">下一页</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
child.vue
<template>
<div>
<div>
<hr>
<h1>我是儿子</h1>
</div>
<Sunzi />
</div>
</template>
<script>
import Sunzi from './sunzi.vue'
export default {
components: {
Sunzi,
},
}
</script>
<style scoped>
</style>
运行如下图所示: