Search code examples
javascriptvue.jsbootstrap-4scopebootstrap-select

How to call a vue method from bootstrap-select listener?


I have a vue with vuex reactive auto-saving app, and I'm using bootstrap-select as one of the fields to try to autosave.

I declare the bootstrap-select listener in the vue component's mounted() lifecycle hook like so:

mounted() {  //vue mounted hook
    const selectpicker = $(this.$el).find('.selectpicker')

    selectpicker.selectpicker('val', this.selected);  //this shows previously saved 'selected' items

    function callback() {
      this.callVueComponentMethod()  //throws 'this.* is not a function'
    }

    selectpicker.selectpicker().on('changed.bs.select', callback()); 
}

I declare it in the mounted hook as this is how I got it to work best... but now I want to try to $emit a function to the parent vue component when a selection changes on the bootstrap-select so I need to somehow access the this object in the bootstrap-select listener to call the $emit up the chain to eventually save the selection change.

I could be missing something but I feel like the problem is getting the this object into the selectpicker listener scope?

Appreciate any and all advice!! thanks :)


Solution

  • Use arrow function which solve this problem.

    let callback = () => {
      this.callVueComponentMethod();
    }
    

    To learn more about this you can read this.