Skip to content

Instantly share code, notes, and snippets.

@sidouglas
Last active February 3, 2021 09:12
Show Gist options
  • Save sidouglas/011d6ef91830cee6c7720dafe30aa864 to your computer and use it in GitHub Desktop.
Save sidouglas/011d6ef91830cee6c7720dafe30aa864 to your computer and use it in GitHub Desktop.
Vue 2 Injector / Provider
export function createProvider (vm) {
const provider = {}
return (properties) => {
properties.forEach((property) => {
const [[key, alias = null]] = typeof property === 'string'
? [[property]]
: Object.entries(property)
Object.defineProperty(provider, key, {
enumerable: true,
get: () => vm[alias || key]
})
})
return provider
}
}
// Vue Component / App
data: () => ({ isRecording: false })
computed:{
clientHasVideo(){
return true
},
exampleHasAudio(){
return false
},
},
provide () {
const provider = createProvider(this)
return ({
nameOfProvider: provider([
'isRecording',
{ hasVideoEnabled: 'clientHasVideo' }, //alias
{ hasAudioEnabled: 'clientHasAudio' }, //alias
])
})
},
...
// child component
inject: ['nameOfProvider'],
// now child component has the following properties - which are reactive to parent changes.
// note do not modify the child provided data, use events.
// this.nameOfProvider.hasVideoEnabled
// this.nameOfProvider.hasAudioEnabled
// this.nameOfProvider.isRecording
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment