Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js access parent component

I've got a child-component that has this method:

getSubscriptions () {
    MessageService.subscriptions()
            this.$parent.loading = true;
            .then((data) => {
                if (data.data.subscriptions == null) {
                    this.noSubscriptions = true;
                } else {
                    this.subscriptions = data.data.subscriptions;
                }

                this.$parent.loading = false;
            }).bind(this);
}

So I want to show a load circle in my parent component I access it like this:

this.$parent.loading

(My parent component has a data attribute called loading)

But when I try to compile that with gulp ^ I receive:

[14:52:56] Starting 'browserify'...
  46 |                             }
  47 | 
> 48 | t                           this.$parent.loading = false;
     |                             ^
  49 |                         }).bind(this);
  50 |             },
  51 | 
{ SyntaxError: unknown: Unexpected token (48:28)
  46 |                             }
  47 | 
> 48 | t                           this.$parent.loading = false;
     |                             ^
  49 |                         }).bind(this);
  50 |             },

What could be wrong here?

(I'm using Vue.js 1.0)

like image 282
Jamie Avatar asked Oct 13 '16 13:10

Jamie


People also ask

How do you access child component method in parent component in VUE JS?

Given a root Vue instance is accessible by all descendants via this. $root , a parent component can access child components via the this. $children array, and a child component can access it's parent via this. $parent , your first instinct might be to access these components directly.

What is $parent in Vue?

How $parent is described in Vue? The $parent property, like $root, can be used for accessing the parent instance from a child. It provides direct access, making the application hard to test and debug.


1 Answers

You're putting a new statement in the middle of a promise setup. You need to rearrange the code:

this.$parent.loading = true;
MessageService.subscriptions()
        .then((data) => {

However, I wouldn't directly access the parent like this. It creates a tight coupling between parent and child -- this component will only work if the parent exposes a loading flag.

Instead, look into custom events.

like image 103
PatrickSteele Avatar answered Sep 22 '22 04:09

PatrickSteele