1

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?

3
  • 1
    you can create a plugin for this kind of use case Commented Dec 24, 2021 at 20:05
  • I don't know how, I will take a look around Commented Dec 26, 2021 at 8:48
  • 1
    please look at this repo this is a demo for notification plugin which I createdhttps://github.com/bhumit070/notification-plugin In this I am using vuetify's toast but you can replace it with sweet alert Commented Dec 26, 2021 at 14:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.