Pedro Moreira
Pedro Moreira

Reputation: 970

Vue.js - "Bind" bootstrap modal to Vue model

So, in my Vue instance, I have a currentTask model, which is null by default.

new Vue({
    el: '...',

    data: {
        currentTask: null
    }
});

When I click on a 'task-item', which has v-on="click: openTask" directive, i want to launch the modal with the currentTask:

methods: {
    openTask: function(e) {
        this.currentTask = this.clickedTask;
        $('#task-modal').modal('show');

        e.preventDefault();
    }
}

This is working just fine, although I don't know if there is a more "magical" way to two-way bind the whole modal + visibility to the currentTask.

Now, what I need, if there is no better way to go about this, is to somehow listen for the modal close event, which normally we would do in jQuery with $('#myModal').on('hidden.bs.modal', function() {}); inside of Vue and set this.currentTask = null;.

Thank you.

Upvotes: 3

Views: 7031

Answers (1)

Kelt
Kelt

Reputation: 361

You could probably use a custom directive to handle this.

Vue.directive('task-selector', {
   bind: function () {
      var vm = this.vm;
      var el = $(this.el);
      el.on('hidden.bs.modal', function() {
         vm.data.currentTask = 'whatever value you want here';
      });
   },
   update: function (newValue, oldValue) {
      // i don't think you have anything here  
   },
   unbind: function () {
      // not sure that you have anything here
      // maybe unbind the modal if bootstrap has that
   }
})

In your html you would need to put this directive on the modal element like so...

<div id="task-modal" v-task-selector>
   ... modal body stuff here...
</div>

Upvotes: 3

Related Questions