Skip to content

Instantly share code, notes, and snippets.

@bakpa79
Last active September 28, 2018 15:00
Show Gist options
  • Save bakpa79/b62b74df99f9ac30e36511795e133722 to your computer and use it in GitHub Desktop.
Save bakpa79/b62b74df99f9ac30e36511795e133722 to your computer and use it in GitHub Desktop.
Vue 2.x Inject registration syntax
//Parent component
export default Vue.extend({
props:{
propValue:{
required:false,
default:false,
type: Boolean
}
},
provide: function(){
const sharedParentObject = {
sharedMethod: this.sharedMethod,
register: this.register,
}
Object.defineProperty(sharedParentObject, 'sharedReactiveVariable', {
enumerable: true,
get: () => this.sharedReactiveVariable,
//Within the scope of the parent component, allows you to update shared reactive Variable
set: (val)=> this.sharedReactiveVariable = val,
})
Object.defineProperty(sharedParentObject, 'sharedReactiveVariable', {
enumerable: true,
get: () => this.sharedValuePopulatedByProp,
})
return {sharedParentObject}
},
data: function(){
return {
//example shared value
sharedReactiveVariable: false,
sharedValuePopulatedByProp: this.propValue,
arrayForRegisteredChildren:[]
}
},
methods:{
sharedMethod(val){
//do something with val
},
// if you want to track the child components in the parent, use register/unregister methods to create
// that relationship through an array in the parent
register(componentAsThis) {
console.log("registering", componentAsThis);
this.arrayForRegisteredChildren.push(componentAsThis);
},
unregister(componentAsThis) {
let index = this.arrayForRegisteredChildren.indexOf(componentAsThis);
if (index > -1) {
// console.log("unregistering", componentAsThis);
this.arrayForRegisteredChildren.splice(index, 1);
}
},
}
})
//Child Component
export default Vue.extend({
props:{
//fixes typescript linting errors, of sharedParentObject not existing on type "Vue"
sharedParentObject:{
type:Object,
default:null,
}
},
inject: {
sharedParentObject: {
//Shared Variables are now accessible, plus you can hoist default methods
default : {
sharedMethod() {},
register(){},
unregister(){}
}
}
},
mounted() {
this.sharedParentObject.register(this)
},
destroyed() {
this.sharedParentObject.unregister(this)
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment