Vue — How to get parent instance in child component

wowissu
2 min readMar 15, 2019

--

Usually you can access ParentComponent like this

created() {
let parent = this.$parent
}

But if we want find specific ParentComponent in deep structure,
we use the recursive one by one to look up.

Here is other way for deep accessing

provider/inject

Normally the injection can get all provider from every ParentComponent’s provider by specific key name
here is example you can have in https://vuejs.org/v2/api/#provide-inject

// parent component providing ‘foo’ 
var Provider = {
provide: { foo: ‘bar’ },
// …
}
// child component injecting ‘foo’
var Child = {
inject: [‘foo’],
created () { console.log(this.foo) // => “bar” }
// …
}

But is only for pure data.
You only get Child instance if you try to access ‘this’ in a function in provider

// parent component providing ‘foo’ 
var Provider = {
provide: {
foo() {
console.log(this) // Child instance
}
},
// …
}
// child component injecting ‘foo’
var Child = {
inject: [‘foo’],
created () {
this.foo()
}
// …
}

Here is an easy way to get ParentComponent

// parent component providing ‘foo’ 
var Provider = {
created () {
this._provided.foo = this
}
// …
}
// child component injecting ‘foo’
var Child = {
inject: [‘foo’],
created () {
console.log(this.foo) // ParentComponent
}
// …
}

Yes ! you can access Specific ParentComponent for now.

Remember is only work on

created() { //… }

Because you need prepare the provider before you mounted child
for created() the order is up to down
but mounted() is down to up, it will exec child’s mounted() first

--

--