Last active
February 3, 2021 09:12
-
-
Save sidouglas/011d6ef91830cee6c7720dafe30aa864 to your computer and use it in GitHub Desktop.
Vue 2 Injector / Provider
This file contains hidden or 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
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