vueRouter
- Vue Router是Vue.js的官方路由管理器,用于构建单页应用中的页面路由。它提供了丰富的功能,包括路由定义、路由跳转、路由参数传递、嵌套路由等,使得开发者能够方便地管理应用的路由结构。
官网
安装
npm install vue-router
Demo
main.js
创建路由
import {createApp} from 'vue'
import './style.css'
import App from './App.vue'
import {createMemoryHistory, createRouter} from "vue-router";
import HelloComp from "./components/HelloComp.vue";
import TestComp from "./components/TestComp.vue";
import HomeComp from "./components/HomeComp.vue";
const router = createRouter({
history: createWebHistory(),
routes: [
{path: '/', component: HomeComp},
{path: '/hello', component: HelloComp},
{path: '/test', component: TestComp},
]
})
const app = createApp(App)
app.use(router)
app.mount('#app')
- 或者单独创建一个文件,然后在main中引入
import {createMemoryHistory, createRouter} from "vue-router";
import Home from "../pages/Home.vue";
import About from "../pages/About.vue";
import Error from "../pages/Error.vue";
const routes = [
{path: '/', component: Home},
{path: '/about', component: About},
{path: '/:pathMatch(.*)*', component: Error},
]
const router = createRouter({
history: createWebHistory(),
routes: routes
})
export default router
App.vue
在<RouterView />中加载路由页面
默认先加载的是{path: '/', component: HomeComp}
<script>
</script>
<template>
<div>Router测试</div>
<RouterView />
</template>
<style scoped>
</style>
HomeComp
- 通过push方法进行跳转
gotoTest() {
console.log("goto test")
this.$router.push('/test')
},
- 返回上一级
gotoBack() {
this.$router.go(-1)
},
<script>
export default {
data() {
return {
btn_name_1: "跳转到:测试二维码页面",
btn_name_2: "跳转到:hello页面",
}
},
methods: {
gotoTest() {
console.log("goto test")
this.$router.push('/test')
},
gotoHello() {
console.log("goto hello")
this.$router.push('/hello')
}
}
}
</script>
<template>
<h1>测试首页</h1>
<div style="display: flex;flex-direction: column">
<button class="btn" v-text="this.btn_name_1" @click="gotoTest()"/>
<button class="btn" v-text="this.btn_name_2" @click="gotoHello()"/>
</div>
</template>
<style scoped>
.btn {
margin: 10px;
}
</style>
其他调用方式
- 通过useRouter()得到实例,来调用push方法
import {useRouter} from "vue-router";
const router = useRouter()
router.push('/about')