Created
June 7, 2019 00:18
-
-
Save TanAlex/1a41b0749908e61c738a2573ac73865b to your computer and use it in GitHub Desktop.
[vue plugin sample]Create vm.$responsive to capture windows size #vue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-ui/src/util/bus.js | |
import Vue from 'vue' | |
const bus = new Vue() | |
export default { | |
install (Vue) { | |
Vue.prototype.$bus = (type, ...args) => { | |
bus.$emit(type, ...args) | |
} | |
Vue.mixin({ | |
beforeCreate () { | |
const busOptions = this.$options.bus | |
if (busOptions) { | |
this.$_bus = [] | |
const addListeners = map => { | |
for (const event in map) { | |
const handler = map[event].bind(this) | |
bus.$on(event, handler) | |
this.$_bus.push({ event, handler }) | |
} | |
} | |
if (Array.isArray(busOptions)) { | |
busOptions.forEach(addListeners) | |
} else { | |
addListeners(busOptions) | |
} | |
} | |
}, | |
beforeDestroy () { | |
if (this.$_bus) { | |
for (const listener of this.$_bus) { | |
bus.$off(listener.event, listener.handler) | |
} | |
} | |
} | |
}) | |
Vue.config.optionMergeStrategies.bus = (parent, child, vm) => { | |
if (Array.isArray(parent)) { | |
if (Array.isArray(child)) { | |
return parent.concat(child) | |
} else { | |
parent.push(child) | |
return parent | |
} | |
} else if (Array.isArray(child)) { | |
child.push(parent) | |
return child | |
} else if (parent && child) { | |
return [parent, child] | |
} else if (parent) { | |
return parent | |
} | |
return child | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-ui/src/util/responsive.js | |
export let responsive | |
export default { | |
install (Vue, options) { | |
const finalOptions = Object.assign({}, { | |
computed: {} | |
}, options) | |
responsive = new Vue({ | |
data () { | |
return { | |
width: window.innerWidth, | |
height: window.innerHeight | |
} | |
}, | |
computed: finalOptions.computed | |
}) | |
Object.defineProperty(Vue.prototype, '$responsive', { | |
get: () => responsive | |
}) | |
window.addEventListener('resize', () => { | |
responsive.width = window.innerWidth | |
responsive.height = window.innerHeight | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment