這裡記錄一下關於 vue-router 的學習,以及自己實現乙個類似的東西
vue-router 分為 hash 模式和 history 模式,眾所周知的是,hash 模式 是利用 監聽 hashchange 事件來實現的,而history 則是通過監聽 popstate 事件 實現的,那麼 到底是在什麼時候實現監聽的呢?
let _vue
export default class vuerouter
vuerouter.install.installed = true
// 2、把vue 建構函式記錄到全域性變數
_vue = vue
}constructor(options)
// 將當前的 data 手動設定為 響應式的
this.data = _vue.observable()
}}
如下, router 是在vue 初始化的時候放到 vue 物件裡的,那麼怎麼在 vuerouter 裡面獲得這個類呢?
import vue from 'vue'
import router from './router'
vue.config.productiontip = false
new vue(, '', '#/')}}
}})
}
init()
initroutemap() )
}
這裡的路由元件包括了router-link和router-view ,關於 slot 屬性不熟悉的,可以看一下vue 中的 $slot 獲取 插槽的節點
initcomponents(vue) ,
// 使用了 vue 的 render 屬性,也相當於是函式式元件
render(h) ,
on:
}, [this.$slots.default])
},methods: , '', mode + this.to)
// 注意的是,這裡的 data.current 在前面已經被手動設定為 被監聽的屬性了
this.$router.data.current = this.to;} }
})const _this = this
vue.component('router-view',
})}
initevent() )
} else )
}}
let _vue
export default class vuerouter
vuerouter.install.installed = true
// 2、把vue 建構函式記錄到全域性變數
_vue = vue
// 3、把建立vue 例項的時候傳入 router 物件
// 混入。
_vue.mixin(, '', '#/')}}
}})
}constructor(options)
// 響應式的
this.data = _vue.observable()
}init()
initroutemap() )
}// 初始化 router-link
initcomponents(vue) ,
render(h) ,
on:
}, [this.$slots.default])
},methods: , '', mode + this.to)
this.$router.data.current = this.to;} }
// tempalet: '
' })
const _this = this
vue.component('router-view', })}
initevent() )
} else )}}
}
// router/index.js
import vuerouter from '../../vue-router/index'
import vue from 'vue'
vue.use(vuerouter)
const routes = [
,]export default new vuerouter()
// main.js
import vue from 'vue'
import router from './router'
vue.config.productiontip = false
new vue({
router,
vue router的理解,以及實現原理
1早期的前端路由的實現就是基於 location.hash 來實現的。其實現原理很簡單,location.hash 的值就是 url 中 後面的內容。比如下面這個 它的 location.hash 的值為 search html5 提供了 history api 來實現 url 的變化。其中做最主要...
Vuerouter學習筆記
vue路由的作用 將元件 components 對映到路由 routes 然後告訴 vue router 在 渲染它們 前端路由是 對映關係 是路徑和元件的對映關係 vuerouter 路由器物件 然後 該物件有routes屬性 其為路由們配置,為陣列,陣列中每個值為乙個路由,路由就是相應的對映 步...
vueRouter學習心得
const user const router newvuerouter 現在呢,像 user foo 和 user bar 都將對映到相同的路由。借助 vue router,使用巢狀路由配置,就可以很簡單地表達這種關係。乙個被渲染元件同樣可以包含自己的巢狀 例如,在 user 元件的模板新增乙個r...