Vue3使用v.4x;Vue2使用v.3x。
-
v.4x基本使用
import { createApp } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
// 1. 定义路由组件.
// 也可以从其他文件导入
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里暂时保持简单
const router = VueRouter.createRouter({
// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
history: VueRouter.createWebHashHistory(),
routes
})
// 5. 创建并挂载根实例
const app = Vue.createApp({})
app.use(router)
app.mount('#app')
// 在setup里面没有访问this,所以我们不能再直接访问this.$router或this.$route。作为替代,我们使用useRouter和useRoute函数。
import { useRouter, useRoute } from 'vue-router'
import { watch } from 'vue'
export default {
setup() {
const router = useRouter()
const route = useRoute()
funtion pushWithQuery(query) {
router.push({
path: 'search',
query: {
...route.query
}
})
}
// 避免监听整个route
// 当参数更改时获取用户信息
watch(() => route.params.id,
async newId => {
userData.value = await fetchUser(newId)
}
)
}
}
// 请注意,在模板中依然可以访问$router 和 $route
-
v.3x基本使用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
/ 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
// 我们晚点再讨论嵌套路由。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
routes // (缩写) 相当于 routes: routes
})
// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
router
}).$mount('#app')
v.4x路由配置404页面方式
{
path: '/404',
name: '404',
component: () => import('@/view/404')
},
{
path: '/:pathMatch(.*)',
redirect: '/404'
}
v.3x路由配置404页面方式
{
path: '*',
name: '404',
component: () => import('@/view/404')
}