Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call bootstrap-vue modals and toasts from vuex actions?

Did anyone tried to use boostrap-vue in combination with vuex? I'm having hard time calling modals and toast from vuex actions.

Obviously I can not use this from vuex store, therefore I can't use:

this.$bvModal.show('modalId');

I also tried calling modal like this

import Vue from 'vue';

Vue.prototype.$bvModal.show('transaction');

But console gives me following warning:

BootstrapVue warn]: '$bvModal' must be accessed from a Vue instance 'this' context

Any idea how I can call modals and toasts from vuex actions directly?

like image 371
Luka Sh Avatar asked Aug 11 '19 07:08

Luka Sh


2 Answers

Try to call this._vm.$bvModal.show('modalId');. Reference.

like image 115
Andrew Vasilchuk Avatar answered Sep 18 '22 12:09

Andrew Vasilchuk


I think a better approach is to prevent to deal with the UI from the Store. So, you can add a store property and watch for changes from your components.

In the following example, I added an array toastMessages in the state property and a ADD_TOAST_MESSAGE mutation to add some toastMessage. You can then commit an ADD_TOAST_MESSAGE mutation from another mutation or from an action.

Inside your Top-level component (App.vue), you can watch for your toastMessages state property changes and display the last item that was pushed.

App.vue

<script>
export default {
  name: "App",
  created() {
    this.$store.watch(
      state => state.toastMessages,
      toastMessages => {
        this.$bvToast.toast(this.toastMessages.slice(-1)[0]);
      }
    );
  }
}
</script>

store.js

export default new Vuex.Store({
  state: {
    toastMessages: []
  },
  mutations: {
    ADD_TOAST_MESSAGE: (state, toastMessage) => (state.toastMessages = [...state.toastMessages, toastMessage]),
  },
  actions: {
    myActionThatDoSomething({commit}, params) {
      // Do something
      commit('ADD_TOAST_MESSAGE', "Something happened");
    }
  }
});
like image 42
eroak Avatar answered Sep 20 '22 12:09

eroak