history和hash模式对比:
- 它们都实现页面的跳转功能一样(跳转页面)
- 它们的区别体现在3个方面
a. 外观:history模式的path路径不带#号,hash有#号
b. 原理:hash模式使用onhashchange , history使用pushState。导致有兼容性的差异。hash模式兼容性好(对浏览器的兼容性,onhashchange ),history的兼容性比hash模式差一些 (底层使用的API是Html5的API: ,对浏览器有一定的要求。 )
c. 项目上线之后有区别。history开发的项目,在打包上线之后,需要后端配置来支持,不然就会出现404页面。官网上有介绍。 - 我在开发中,没有特殊的要求,一般就用hash。如果要修改模式,就改mode: “history”
- 为啥会有404页面?
a. history访问这个地址时, http://www.xxx.com/find ,后端收到的 req.url 是 /find, 但是我们是单页应用程序,我们只有一个资源是index.html,没有资源叫/find,所有就会报404。
b. history访问这个地址时, http://www.xxx.com/#/find ,后端收到的 req.url 是 /, 有一个资源是index.html,能正常显示
参考一
// 导入路由插件
import VueRouter from 'vue-router'
import Vue from 'vue'
// 使用插件 - 重要
Vue.use(VueRouter)
// 导入组件
import Page1 from './Page1.vue'
import Page2 from './Page2.vue'
import Page3 from './Page3.vue'
// 创建路由规则
const router = new VueRouter({
routes: [
{
path: "/page1", // 当浏览器访问 http://localhost:8080/#/page1时,
component: Page1 // 装入组件 Page1
},
{
path: "/page2",
component: Page2
},
{
path: "/page3",
component: Page3
}
]
})
export default router
参考二
//配置路由
//写一段固定代码
// 导入路由插件
import VueRouter from 'vue-router'
import Vue from 'vue'
// 使用插件 - 重要
Vue.use(VueRouter)
// 导入组件
import MyNews from '../50--路由/pages/MyNews.vue'
import MyHome from '../50--路由/pages/MyHome.vue'
import MyMovie from '../50--路由/pages/MyMovie.vue'
import Pag404 from '../50--路由/pages/Pag404.vue'
// 创建路由规则
const router = new VueRouter({
routes: [{
path: '/',
redirect: '/home'
},
/* { //进入a跳入b
path: '/a',
redirect: '/b'
},
*/
{
path: "/home", // 当浏览器访问 http://localhost:8080/#/index时,
component: MyHome // 装入组件 MyHome
},
{
name: 'movie',
path: "/movie", // 当浏览器访问 http://localhost:8080/#/movie时,
component: MyMovie // 装入组件 MyMovie
},
当浏览器访问 http://localhost:8080/#/news 拿不到 无法匹配
当浏览器访问 http://localhost:8080/#/news/123 id是 123
当浏览器访问 http://localhost:8080/#/news/3456 id是 3456
{
// path: "/news/:id/:name", //多个查询 是加参数
path: "/news/:id", //详情页 给id
component: MyNews // 装入组件 MyMovie
},
{
//默认匹配404
path: '*',
component: Pag404
}
]
})
export default router
vue官网
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
]
const router = new VueRouter({
// mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
其他模板
更新中!