1. vue-router
class Vrouter {
/**
* options: 就是 路由信息表
*
*
**/
constructor(Vue,options){
this.$options = options
this.routeMap = {}
this.app = new Vue({
data: {
current : '#/'
}
})
this.init()
this.createRouteMap(this.$options)
this.initComponent(Vue)
}
// 初始化 hashchange
init(){
// 这里初始化时 监听 hash的值
window.addEventListener('load', this.onHashChange.bing(this),false)
// 这里监听 hash 的变化
window.addEventListener('hashchange', this.onHashChange.bind(this),false)
// history模式
window.addHistoryListener('history',function(){
console.log('窗口的history改变了');
})
window.addHistoryListener('history',function(){
console.log('窗口的history改变了-我也听到了');
})
}
/**
* 匹配组件 这里 从路由信息表中 把 路径 和 组件 进行匹配
* 如: '/home' : Home
*
*/
createRouteMap(options){
options.routes.forEach(item => {
this.routeMap[item.path] = item.component
})
}
// 渲染组件
initComponent(Vue){
Vue.component('router-link',{ // 这里实际上是在全局注册了一个 a 标签
props: {
to: String
},
render: function(h){
return h(
'a',
{
attrs: {
href: this.to
}
},
this.$slots.default
)
}
})
const _this = this
Vue.component('router-view',{ // 这里拿到路径对应 的组件 渲染到 router-view 占位符的位置
render(h) {
var component = _this.routeMap[_this.app.current]
return h(component)
}
})
}
// 获取当前hsah
getHash(){
return window.location.hash.slice(1) || '/' // 截取hash
}
// 设置当前路径
onHashChange(){
this.app.current = this.getHash()
}
}
2.vueX
class Vstore {
constructor(options){
this.state = options.state
this.mutations = options.mutations
this.actions = options.actions
// 这里实际上还是 借用vue 本身的数据响应机制,才让页面可以实时更新数据的
new Vue({
data: {
state: this.state
}
})
}
commit(type,paylod){
const mutation = this.mutations[type]
mutation(this.state,paylod)
}
dispatch(type, paylod){
const action = this.actions[type]
const ctx = {
commit: this.commit.bind(this),
state: this.state
}
return action(ctx.paylod)
}
}
学习更多的知识请关注《程序员宅男屋》!!!