Skip to content
Advertisement

Define global variables to use inside components

I have a Laravel 8 project, with vue-sweetalert2 installed. I’d like to define the Toast behaviour once, and then call it inside my components.

By now I have this code:

/js/components/Mypage.vue

JavaScript

This works fine, of course, but as you can see Toast is defined inside the method, and I cannot re-use it somewhere else.

I’d like to define it inside app.js (maybe) and than access it everywhere, but if I move the code inside app.js as is, I receive an error, that tells me that $swal is not defined. I tried to use Swal instead of $swal… nothing changed.

/js/app.js

JavaScript

So, how can I define the Toast once?

Advertisement

Answer

It looks like you’re trying to setup the SweetAlert instance (this.$swal in your components) with initialization options. That could be done when installing the vue-sweetalert plugin. The second argument to Vue.use() is for the plugin options:

JavaScript

demo

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement