配置router
import router from './router'
const app = createApp(App)
app.use(router)
createRouter的使用
import { createRouter, createWebHashHistory } from 'vue-router'
const routes = [
{
path: '/about',
name: 'About',
component: () => import( '../views/About.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
不同的历史模式
createWebHashHistory:有 # 描点值
它在内部传递的实际 URL 之前使用了一个哈希字符(#
)。由于这部分 URL 从未被发送到服务器,所以它不需要在服务器层面上进行任何特殊处理。不过,它在 SEO 中确实有不好的影响。
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes: [
//...
],
})
createWebHistory:没有 # 描点值
用 createWebHistory()
创建 HTML5 模式,推荐使用这个模式:
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
//...
],
})
使用这种历史模式时,URL 会看起来很 "正常",例如 https://example.com/user/id
。
不过,问题来了。由于我们的应用是一个单页的客户端应用,如果没有适当的服务器配置,用户在浏览器中直接访问 https://example.com/user/id
,就会得到一个 404 错误。
要解决这个问题,你需要做的就是在你的服务器上添加一个简单的回退路由。如果 URL 不匹配任何静态资源,它应提供与你的应用程序中的 index.html
相同的页面。
location / {
try_files $uri $uri/ /index.html;
}
createMemoryHistory:基于内存,移动端多
创建一个基于内存的历史。该历史的主要目的是为了处理服务端渲染。它从一个不存在的特殊位置开始。用户可以通过调用 router.push
或 router.replace
将该位置替换成起始位置。
Vue3与Vue2对比
- 对404的配置:vue3把vue2 path路径更改了
// Vue3
{
path:'/:catchAll(.*)',
component: ()=> import('../views/NotFund.vue')
}
// Vue2
{
path:'*',
component: ()=> import('../views/NotFund.vue')
}
- 获取$router和$route方式不同
- useRouter
- useRoute
- 引入router.js中的router
import { useRouter } from 'vue-router';
const router = useRouter;
const goHome = ()=>{
router.push({name:'home'})
}