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

<script>
export default {
    data: function () {
        return { ... };
    },
    mounted() { ... },
    methods: {
        myMethod: function () {
            const Toast = this.$swal.mixin({
                toast: true,
                showConfirmButton: false,
                timer: 2000,
                timerProgressBar: false,
            });
            axios
                .post("/api/something")
                .then((res) => {
                    Toast.fire({
                        icon: "success",
                        title: "Tessera rinnovata",
                    });
                });
...
</script>

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

import VueSweetalert2 from "vue-sweetalert2";
import "sweetalert2/dist/sweetalert2.min.css";

window.Vue = require("vue").default;
import VueRouter from "vue-router";

Vue.use(VueRouter);
Vue.use(VueSweetalert2);

const Toast = $swal.mixin({
    toast: true,
    showConfirmButton: false,
    timer: 2000,
    timerProgressBar: false,
});

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:

// js/app.js
import Vue from 'vue'
import VueSweetAlert from 'vue-sweetalert2'

Vue.use(VueSweetAlert, {
  toast: true,
  showConfirmButton: false,
  timer: 2000,
  timerProgressBar: false,
})

demo

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