0

I have bootstrap (4.3) modal in vuejs app. On modal show I want to send gtag (google analytics) data. I have tried

async created() {
//some other code
 $('#modalRecommend').on('shown.bs.modal', function (e) {
    this.gtagFunction('pressed', 'my cat','test label','no');
    $('body').addClass('modal-recommend-open');
  }).on('hidden.bs.modal', function (e) {
    $('body').removeClass('modal-recommend-open');
  });
 }

When modal show it is showing error

Uncaught TypeError: this.gtagFunction is not a function

If I place this.gtagFunction() this outside $('#modalRecommend').on('shown.bs.modal', function (e) {.. then it is works.

Note: I have loaded a mixins in parent component where this.gtagFunction() is available. Also I have tried to add @click.native in HTML like

<img @click.native="sendAnalytics()" class="w-auto mr-2" src="/pic.png" width="120" height="40" v show="recommendRankingWorks.length > 0" data-toggle="modal" data-target="#modalRecommend" style="cursor:pointer;"/>

with

methods{
sendAnalytics: function(){
            this.gtagFunction('pressed', 'my cat','test label','no');
        },
}

but not fired. Only show modal

1
  • u can replace function to arrow function. E.g. function() {} to () => {} Commented Mar 21, 2019 at 9:13

1 Answer 1

2

When you called

$('#modalRecommend').on('shown.bs.modal', function (e) {
    this.gtagFunction('pressed', 'my cat','test label','no');

this is not bounded to Vue instance, but to the jQuery object $('#modalRecommend'). That's why you cannot access gtagFunction defined in your Vue component.

Since you can call the function outside of jQuery call, you can try to call gtagFunction like this:

const { gtagFunction } = this;
$('#modalRecommend').on('shown.bs.modal', function (e) {
    gtagFunction('pressed', 'my cat','test label','no');
Sign up to request clarification or add additional context in comments.

1 Comment

I have just use let self = this;self.gtagFunction('pressed', 'my cat','test label','no'); and now working. Perhaps your solution will also will work. I have got the idea from your answer. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.