function a() { console.log('函数自己的方法'); } a.install = function () { console.log('install的方法'); } Vue.use(a)//install的方法复制代码
a.install = function (Vue) { Vue.mixin({ data(){ return{ //均可以在任何组件调用这个name name:"zxx" } } }) }复制代码
//能够拿到各个组件实例的this created(){ console.log(this); }复制代码
//vue外面的对象 var test={ testa:1 } //进行数据绑定 Vue.util.defineReactive(test,'testa') //2秒以后改变 setTimeout(function(){ test.testa=333 },2000) a.install = function (Vue) { Vue.mixin({ //混入下面的组件 beforeCreate(){ this.test=test }, created(){ } }) }复制代码
代码前端
class History { constructor() { this.current = null } } class VueRouter { constructor(options) { this.mode = options.mode || 'hash'; this.routes = options.routes || []; this.history = new History; this.routesMap = this.createMap(this.routes) this.init() } init() { if (this.mode === 'hash') { //若是为false的话,那么执行后面的语句,改为/ //若是为true的话,执行'',不改变任何东西 location.hash ? '' : location.hash = '/'; window.addEventListener('load', () => { this.history.current = location.hash.slice(1) }) window.addEventListener('hashchange', () => { this.history.current = location.hash.slice(1) }) } else { location.pathname ? '' : location.pathname = '/'; window.addEventListener('load', () => { this.history.current = location.pathname }) window.addEventListener('popstate', () => { this.history.current = location.pathname }) } } createMap(routes) { return routes.reduce((prev, item) => { prev[item.path] = item.component return prev }, {}) } } VueRouter.install=function(Vue){ Vue.mixin({ //全局混入了router实例,而且作了响应式绑定 beforeCreate() { if (this.$options && this.$options.router) { this._root = this; this._router = this.$options.router Vue.util.defineReactive(this, 'current', this._router.history) } else { this._root = this.$parent._root } } }) Vue.component('router-view', { render(h) { let current = this._self._root._router.history.current; console.log(current); let routesMap = this._self._root._router.routesMap console.log(routesMap); return h(routesMap[current]) } } ) } export default VueRouter复制代码