基礎(chǔ)入門文檔建議直接查看React中文文檔,這樣能少走很多彎路,
官方文檔地址:Vue Router
路由設(shè)置
router/index.js文件,管理路由器的創(chuàng)建:
import Vue from 'vue'
import Router from 'vue-router'
import Index from './views/index.vue' //直接加載
const Product = () => import('@/views/product.vue'); //懶加載
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Index ',
component: Index ,
},
{
path: '/product ',
name: 'Product ',
component: Product ,
},
]
})
路由跳轉(zhuǎn)
第一種使用方式:
<router-link to='/'>首頁</router-link>
<router-link to='/product'>子頁面</router-link>
第二種使用方式
this.$router.push('/')
this.$router.push('/product')
路由傳參
this.$router.push({ name: 'product', params: { userId: 123 }}) //類似post傳參
this.$router.push({ path: 'product', query: { plan: 'private' }}) //類似get傳參
History 模式
vue-router 默認(rèn) hash 模式 —— 使用 URL 的 hash 來模擬一個(gè)完整的 URL,于是當(dāng) URL 改變時(shí),頁面不會(huì)重新加載。
如果不想要很丑的 hash,我們可以用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉(zhuǎn)而無須重新加載頁面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
不過這種模式要玩好,還需要后臺(tái)配置支持。因?yàn)槲覀兊膽?yīng)用是個(gè)單頁客戶端應(yīng)用,如果后臺(tái)沒有正確的配置,當(dāng)用戶在瀏覽器直接訪問就會(huì)返回 404,這就不好看了。
所以呢,你要在服務(wù)端增加一個(gè)覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態(tài)資源,則應(yīng)該返回同一個(gè) index.html 頁面,這個(gè)頁面就是你 app 依賴的頁面。這里只說nginx的配置。
nginx的配置
location / {
try_files $uri $uri/ /index.html;
}
image.png
說明:
這里root有兩種設(shè)置,如果直接以www.xxxx.com/這種域名方式訪問
location / {
root html/文件名;
}
如果直接以www.xxxx.com/admin/這種域名方式訪問
location / {
root html;
}
不過前端路由的路徑就要改動(dòng),在每個(gè)路徑前面加上/admin
警告:
給個(gè)警告,因?yàn)檫@么做以后,你的服務(wù)器就不再返回 404 錯(cuò)誤頁面,因?yàn)閷?duì)于所有路徑都會(huì)返回 index.html 文件。為了避免這種情況,你應(yīng)該在 Vue 應(yīng)用里面覆蓋所有的路由情況,然后在給出一個(gè) 404 頁面。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})