user3921266
user3921266

Reputation:

Call component methods outside component

I am fairly new to Vue.js and I might be thinking about this the wrong way, in which case I would really appreciate the help.

I have a component defined as below:

Vue.component('btn', {

data() {

    return {
        active: false
    };

},

props: ['type', 'msg'],

template: "<button class='btn__{{ type }}'><div class='la-ball-scale-multiple' v-show='active'><div></div><div></div><div></div></div>{{ msg }}</button>",


methods: { 

    start: function() {
        this.active = true;

    },

    stop: function() {
        this.active = false;
    }

}
});

and I can add the btn component multiple times on any document, like this:

<btn type="primary" msg="Submit" @click="test"></btn>

When I click on it, it should do whatever is defined in test, which is in the root vue instance as a method.

However, I want to call the component's method, start in the test method. I also want to be able to call the component's stop method when I am done with the code logic inside test.

I don't think exposing the methods as events within the component and then calling this.$broadcast is a solution because, if I have two components, both of them seem to set active to true with this solution.

Any help please?

Upvotes: 1

Views: 1513

Answers (1)

nils
nils

Reputation: 27184

You could pass in your test function as a prop (called onclick for example) and then pass the context of your btn component as an argument to the test function. That way, you could access start and stop.

test:

test: function(e, btn) {
   btn.start();
   // ...
   btn.stop();
}

btn:

Vue.component('btn', {

data() {

    return {
        active: false
    };

},

props: ['type', 'msg', 'onclick'],

template: "<button class='btn__{{ type }}' @click="btnClick($event)"><div class='la-ball-scale-multiple' v-show='active'><div></div><div></div><div></div></div>{{ msg }}</button>",


methods: { 

    start: function() {
        this.active = true;

    },

    stop: function() {
        this.active = false;
    },

    btnClick: function(e) {
       this.onclick(e, this); // call your onclick handler in the context of this component
    },

}
});

custom element:

<btn type="primary" msg="Submit" :onclick="test"></btn>

Have a look at the JSFiddle:

https://jsfiddle.net/2a5os24x/6/

Upvotes: 2

Related Questions