https://router.vuejs.org/zh/guide/#html
基础
入门
加入 Vue Router 时,将组件映射到路由上。
router-link 使得 Vue Router 可以在不重新加载页面的情况下更改 URL,处理 URL 的生成以及编码。
router-view 将显示与 url 对应的组件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
const Home = { template: '<div>Home</div>' } const About = { template: '<div>About</div>' }
const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, ]
const router = VueRouter.createRouter({ history: VueRouter.createWebHashHistory(), routes, })
const app = Vue.createApp({})
app.use(router)
app.mount('#app')
|
通过调用 app.use(router),我们可以在任意组件中以 this.$router 的形式访问它,并且以 this.$route 的形式访问当前路由:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| export default { computed: { username() { return this.$route.params.username }, }, methods: { goToDashboard() { if (isAuthenticated) { this.$router.push('/dashboard') } else { this.$router.push('/login') } }, }, }
|
要在 setup 函数中访问路由,请调用 useRouter 或 useRoute 函数。