Vue进阶:vue 路由的两种模式:hash与history_vue创建中的history
warning:
这篇文章距离上次修改已过208天,其中的内容可能已经有所变动。
在Vue中,vue-router提供了两种路由模式:hash模式和history模式。
- Hash模式(默认模式)
Hash模式是使用URL的hash部分(即#
标记后的部分)来模拟一个完整的URL,主要是为了兼容旧的服务端。
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './components/Home.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
// 更多路由配置...
]
const router = new VueRouter({
mode: 'hash', // 使用hash模式
routes
})
new Vue({
router,
// 更多选项...
}).$mount('#app')
- History模式
History模式利用了HTML5 History API,可以让URL看起来更加整洁。但是,在History模式下,你的服务器需要正确地返回index.html页面(单页面应用的入口),对于任意的路由请求都返回这个页面。
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './components/Home.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
// 更多路由配置...
]
const router = new VueRouter({
mode: 'history', // 使用history模式
routes
})
new Vue({
router,
// 更多选项...
}).$mount('#app')
在服务器端,你需要配置一个回退页面,当URL不对应任何静态资源时,应该返回index.html
文件。这样,你的Vue应用就可以接管路由处理。
评论已关闭