基礎入門文檔建議直接查看React中文文檔,這樣能少走很多彎路,
官方文檔地址:Vue Router
路由設置
router/index.js文件,管理路由器的創建:
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 ,
},
]
})
路由跳轉
第一種使用方式:
<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 默認 hash 模式 —— 使用 URL 的 hash 來模擬一個完整的 URL,于是當 URL 改變時,頁面不會重新加載。
如果不想要很丑的 hash,我們可以用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉而無須重新加載頁面。
const router = new VueRouter({
mode: 'history',
routes: [...]
})
不過這種模式要玩好,還需要后臺配置支持。因為我們的應用是個單頁客戶端應用,如果后臺沒有正確的配置,當用戶在瀏覽器直接訪問就會返回 404,這就不好看了。
所以呢,你要在服務端增加一個覆蓋所有情況的候選資源:如果 URL 匹配不到任何靜態資源,則應該返回同一個 index.html 頁面,這個頁面就是你 app 依賴的頁面。這里只說nginx的配置。
nginx的配置
location / {
try_files $uri $uri/ /index.html;
}
image.png
說明:
這里root有兩種設置,如果直接以www.xxxx.com/這種域名方式訪問
location / {
root html/文件名;
}
如果直接以www.xxxx.com/admin/這種域名方式訪問
location / {
root html;
}
不過前端路由的路徑就要改動,在每個路徑前面加上/admin
警告:
給個警告,因為這么做以后,你的服務器就不再返回 404 錯誤頁面,因為對于所有路徑都會返回 index.html 文件。為了避免這種情況,你應該在 Vue 應用里面覆蓋所有的路由情況,然后在給出一個 404 頁面。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})