1.main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App)
.use(router)
.mount('#app')
2.在src里配置一个router文件夹,里面有index.js
,记得提前准备好Hello.vue文件和Nohello.vue文件,我是只在里面放了个按钮
import { createRouter, createWebHashHistory } from 'vue-router'
import nihao from '../views/Hello.vue'
import nibuhao from '../views/Nohello.vue'
const routes = [
{
path: "/hello",
name: "one",
component: nihao
},
{
path: "/nohello",
name: "two",
component: nibuhao
},
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
3.在App.vue里放入路由出口<router-view/>
<template>
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<router-view/>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
<style>
</style>
运行后页面先是这样子
修改网址
如果你想点击按钮跳转路由,这样子设置即可
<button @click="navigateToAbout">跳转到Nohello</button>
<script>
export default {
methods: {
navigateToAbout() {
this.$router.push('/nohello'); // 使用目标路由的路径进行导航
}
}
}
</script>
嵌套路由
当你想在一个路由页面里跳转到子路由里面,(app01里面只有一句话)
{
path: "/nohello",
name: "AA",
component: nibuhao,
children:[
{
path:"one",//此时路由就不用加/了,router会帮你加的
component:app01
}
]
}
最关键的一步,一定要在Nohello.vue里加上 <router-view/>
<template>
<div>
<button>nohello</button>
<router-view/>
</div>
</template>
页面效果
注意如果是要按钮操作到跳转到子路由,路由一定要写全了
this.$router.push('/nohello'); // 使用目标路由的路径进行导航
这样写不对
像这句话一定要写成
this.$router.push('/nohello/one'); // 使用目标路由的路径进行导航