vue-router4
时间: 2023-12-12 08:34:21 浏览: 150
Vue Router是Vue.js官方的路由管理器。它和Vue.js的核心深度集成,让构建单页面应用变得易如反掌。Vue Router 4是Vue Router的最新版本,相比于Vue Router 3,它有一些新特性和改进。下面是Vue Router 4的一些介绍和演示:
1.安装Vue Router 4
```shell
npm install vue-router@4 --save
```
2.创建路由
```javascript
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
const routes = [
{
path: '/',
name: 'Home', component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
const router = createRouter({
history: createWebHistory(), routes
})
export default router
```
3.在Vue应用中使用路由
```javascript
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
```
4.在组件中使用路由
```javascript
<template>
<div>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</div>
</template>
```
5.获取路由参数
```javascript
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
console.log(route.params.id)
}
}
```
6.编程式导航
```javascript
import { useRouter } from 'vue-router'
export default {
setup() {
const router = useRouter()
const jumpTo = () => router.push('/about')
return {
jumpTo
}
}
}
```
阅读全文