vue 路由的mode(模式)有幾種, 分別是什麼?在那些環境下運行?javascript
路由的使用步驟html
安裝 vue-router yarn add vue-router -S
vue
在src目錄下建立一個router目錄, 裏面建立一個index.js文件 , 這個目錄就是router的模塊java
引入第三方的依賴包, 並註冊路由android
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use( VueRouter ) //使用vue-router這個第三方插件
注意: import這個關鍵字要放在整個文件的上層vue-router
建立了一個router對象實例,而且建立路由表編程
const routes = [ { path: '/home', component: Home }//每個對象就是一個路由 ] const router = new VueRouter({ routes//路由表 必寫的 mode: 'history' //(設置好路由的模式有hash ,history)不設置這個會出現# })
導出router實例
export default router
後端
入口文件main.js中引入路由實例 router , 而後在根實例中註冊api
import router from './router/index.js' new Vue({ router, render: (h) => App }).$mount('#app')
給路由一個路由展現區域瀏覽器
<router-view />
當頁面第一次的打開的時候, 須要作一個重定向, 就是要自動跳轉到 /home 這個路由上
const routes = [ { //咱們要求這個路由的配置要放在路由表的最上方 path: '/', redirect: '/home' } ]
業務: 錯誤路由匹配,
const routes = [ { path: '/', redirect: '/home' //重定向 }, { path: '/home', component: Home }, { path: '/list', component: List }, { path: '/detail', component: Detail }, { path: '/login', component: Login }, { path: '/register', component: Register }, { path: '/user', component: User }, { path: '/shopcar', component: Shopcar }, { path: '/error', component: Error }, { //這個就是錯誤路由匹配, vue規定這個必須放在最下面,它必須將上面的路由全找一遍,找不到才用當前這個 path: '**', redirect: '/error' } ]
vue路由模式的肯定 mode
若是你使用的是 hash , 那麼a標籤就能夠了、
若是你使用 history , 那麼咱們最好將a標籤改爲 router-link 這個組件
二級路由
const routes = [ { path: '/shopcar', component: Shopcar, children: [ { path: 'yyb', //不寫 / component: Yyb } ] } ]
命名路由
做用: 就是簡寫路徑了
{ path: '/shopcar', component: Shopcar, //子路由 children: [ { path: 'yyb', // 容易犯錯點 /yyb X component: Yyb, name: 'yyb' //命名路由 }, { path: 'junge', component: Junge } ] },
使用:
<router-link :to = "{name:'yyb'}"/>
// vue.config.js中能夠默認直接使用 http-proxy-middleware module.exports = { devServer: { proxy: { '/douban': { // /douban 是一個標記 target: 'http://api.douban.com', // 目標源 changeOrigin: true, // 修改源 pathRewrite: { '^/douban': '' } }, '/siku': { target: 'https://android.secoo.com', changeOrigin: true, pathRewrite: { '^/siku': '' } } } } }
<router-link :to = "{name: 'list',params: {id: xxx}, query: {xxx:xxx}}"></router-link>
路由的接參
id: this.$route.params.id query: this.$route.query.xxx
編程式導航 5分鐘
this.$router.push('/home')
業務:
做用: --- 相似 【保安】
導航守衛一共有三種形式
A: 全局導航守衛
router.beforeEach(fn)
B: 路由獨享守衛 beforeEnter
C: 組件內守衛
組件內的前置守衛 beforeRouteEnter((to,from,next)=>{})
next(vm => { //vm指的就是組件 const result = JSON.parse(res.data.slice(7,-1)).rp_result.categorys vm.$set(vm.category,'categorys',result) })
組件內的後置守衛
- 當好離開組件時,調用
- this是能夠訪問到
組件內的更新守衛( 路由傳參和路由的接參 )
this
功能: 導航守衛能夠監聽路由變化狀況
名詞
關於next的使用
業務: 當咱們進入到一個項目的首頁時,可是當咱們沒有註冊帳號時,它主動跳轉到了註冊/登陸頁
router.beforeEach((to,from,next)=>{ const name = localStorage.getItem('name') if( name || to.path === '/login' ){ //若是有 / --> /home next() }else{ next('/login') } })