一、vue-router 兩種模式前端
(1)mode:hash,hash模式背後的原理是onhashchange
事件,能夠在window
對象上監聽這個事件。vue默認爲hash模式vue
window.onhashchange = function(event){ console.log(event.oldURL, event.newURL); let hash = location.hash.slice(1); document.body.style.color = hash; }
(2)mode:historyvue-router
const router = new VueRouter({ mode:"history", routes:[] })
不怕前進,不怕後退,就怕刷新F5,若是後端沒有準備的話,刷新是實實在在地去請求服務器的。後端
在hash模式下,前端路由修改的是#中的信息,而瀏覽器請求時是不帶它玩的,因此沒有問題,可是在history下,你能夠自由的修改path,當刷新時,若是服務器中沒有相應的響應或者資源,會刷出一個404來。瀏覽器
二、嵌套路由服務器
<script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <div id="app"> <p> <router-link to="/user/foo">/user/foo</router-link> <router-link to="/user/foo/profile">/user/foo/profile</router-link> <router-link to="/user/foo/posts">/user/foo/posts</router-link> </p> <router-view></router-view> </div>
const User = { template: ` <div class="user"> <h2>User {{ $route.params.id }}</h2> <router-view></router-view> </div> ` } const UserHome = { template: '<div>Home</div>' } const UserProfile = { template: '<div>Profile</div>' } const UserPosts = { template: '<div>Posts</div>' } const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, children: [ // UserHome will be rendered inside User's <router-view> // when /user/:id is matched { path: '', component: UserHome }, // UserProfile will be rendered inside User's <router-view> // when /user/:id/profile is matched { path: 'profile', component: UserProfile }, // UserPosts will be rendered inside User's <router-view> // when /user/:id/posts is matched { path: 'posts', component: UserPosts } ] } ] }) const app = new Vue({ router }).$mount('#app')
三、嵌套命名視圖app
<script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <div id="app"> <h1>Nested Named Views</h1> <router-view></router-view> </div>
const UserSettingsNav = { template: ` <div class="us__nav"> <router-link to="/settings/emails">emails</router-link> <br> <router-link to="/settings/profile">profile</router-link> </div> ` } const UserSettings = { template: ` <div class="us"> <h2>User Settings</h2> <UserSettingsNav/> <router-view class ="us__content"/> <router-view name="helper" class="us__content us__content--helper"/> </div> `, components: { UserSettingsNav } } const UserEmailsSubscriptions = { template: ` <div> <h3>Email Subscriptions</h3> </div> ` } const UserProfile = { template: ` <div> <h3>Edit your profile</h3> </div> ` } const UserProfilePreview = { template: ` <div> <h3>Preview of your profile</h3> </div> ` } const router = new VueRouter({ mode: 'history', routes: [ { path: '/settings', // You could also have named views at tho top component: UserSettings, children: [{ path: 'emails', component: UserEmailsSubscriptions }, { path: 'profile', components: { default: UserProfile, helper: UserProfilePreview } }] } ] }) router.push('/settings/emails') new Vue({ router, el: '#app' })