Is there a way to implement Bootstrap 5 toast in Vue.js and navigate to a different page, such as after submitting a form?

Is there a way to incorporate the bootstrap5 toast in vuejs while also redirecting to another page? For example, after submitting a form and being redirected to a new page, I would like a toast message to appear with the statement "Your form has been submitted."

form is submitted.

Answer №1

If you're looking to manage state in Vue, you can utilize either eventbus or Vuex. Here's a simple example using Vuex. Check out the live demo with Vue3 Here.

const { Toast } = bootstrap

// Vue component for Home
const Home = {
  template: `
    <div>
      <h5>Home</h5>
      <router-link to="/1">Page 1</router-link>
    </div>
  `
}

// Vue component for Page
const Page = {
  template: `
    <div>
      <h5>Page 1</h5>
      <form>
        <h6>Form</h6>
        <button class="btn btn-primary" @click="handleSubmit">Submit</button>
      </form>
    </div>
  `,
  methods: {
    handleSubmit() {
      this.$store.dispatch('setToast', true)
      this.$router.push('/')
    }
  }
};

const routes = [
  { path: '', component: Home },
  { path: '/1', component: Page }
]

const router = new VueRouter({
  routes
});

const store = new Vuex.Store({
  state: {
    toast: false
  },
  mutations: {
    updateToast(state, payload) {
      state.toast = payload;
    }
  },
  actions: {
    setToast({ commit }, data) {
      commit("updateToast", data);
    },
  },
  getters: {
    getToast(state) {
      return state.toast;
    }
  }
});

new Vue({
  el: "#app",
  router,
  store,
  methods: {
    submitHandler() {
      const toast = new Toast(this.$refs.toast)
      toast.show()
      this.$store.dispatch('setToast', false)
    }
  },
  computed: {
    toastState() {
      return this.$store.getters.getToast
    }
  },
  watch: {
    toastState(newT, oldT) {
      if (newT) this.submitHandler()
    }
  }
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-router"></script>
<script src="https://unpkg.com/vuex"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="20424f4f54535452415060150e110e13">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ffdf0f0ebecebedfeefdfaab1aeb1ac">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<div id="app">
  <h3>Demo</h3>
  <router-view></router-view>
  <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
    <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true" ref="toast">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">TOAST</strong>
        <small>just now</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        form is submitted.
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent the submission of the form if the textfield does not contain any

Is there a way to prevent form submission when a textfield is empty? Currently, my script allows for new empty records to be inserted into the database even when the textfield is empty. $(document).ready(function(){ $("#form1").on('submit', ...

Using Single Quotes as Parameters in JavaScript

I'm currently facing an issue with a function that is designed to populate a field in the parent window when clicked. Specifically, it is meant to fill in a text field with a name. The challenge I am encountering arises when the field contains a sing ...

Chained module incorporating a specialized Angular form validation directive

I've been working on incorporating an angular form validation "plugin," but I've hit a roadblock trying to utilize the directive in a child module. As a test, I'm using the HighlightDirective example. @Directive({ selector: '[highligh ...

How to enable the Copy to Clipboard feature for multiple buttons and transition from using an ID to a class identifier

Can someone please assist me? I have a copy to clipboard function that works well for IDs and a single button on my website. However, I need to modify it to work for multiple buttons and values with a class identifier. Unfortunately, I am unsure how to mak ...

Exploring the concept of generator functions in ES6

I'm grappling with understanding JS generators and why the asynchronous operations in the example below are returning undefined. I thought that using yield was supposed to wait for asynchronous calls to finish. function getUsers(){ var users; $.aj ...

The function to refresh content is causing errors in the code

Creating a comment and replies form where the replies display underneath each comment. I've encountered an issue where I can post replies normally, but when attempting to delete a reply, I must refresh the page. After refreshing, I'm only able to ...

Delivering Django and Vue applications efficiently through an Nginx server

I have a website that utilizes Django for the API and Vue for the frontend. When deploying the site, my current process involves: Generating a production build of the Vue app (npm run build) Transferring the Vue dist folder to a specific directory within ...

Identifying when a user closes a tab or browser to trigger a logout in JavaScript with Vue.js using the Quasar framework

Is there a way to trigger the logout function only when the tab or browser is closed, and not when the page is refreshed? I attempted the following code example, which successfully triggers the logout on tab close but also logs out when the page is ref ...

Elements that are added dynamically do not contain any space between each other

I have a markup template that looks like this. <template id="unsequenced-template"> <button type="button" class="btn btn-primary railcar"></button> </template> Then, I use the following JavaScript ...

My Node/Express service seems to be generating a span in the logs, but I am unable to locate my service in the Ja

Currently, I am in the process of setting up Jaeger tracing for my Node.js microservice using Express.js. After adding a basic GET request handler in my Express app and hitting the endpoint via curl, I notice that a span is created in the logs. However, w ...

How can I smoothly navigate to the top of a page using AngularJS?

After receiving an ajax call response using angularjs, I am looking to automatically scroll to the top of the page. The purpose is to bring focus to alert messages displayed at the top of the page upon receiving the ajax response. Appreciate any guidance ...

What causes Chrome Extension Images to appear broken when they are inserted into the DOM?

Currently working on a Chrome extension, I am attempting to insert a div with a background image into the DOM using a content script. The CSS is loading correctly, and upon inspecting the Developer Tools, the image URL appears to be correct. $('.clos ...

utilizing angularjs and bootstrap to manage multiple button models

Recently delved into learning angularjs and bootstrap. Found a tutorial on creating buttons. <div ng-controller="ButtonsCtrl"> <h4>Checkbox</h4> <pre>{{checkModel}}</pre> <div> <button type="butto ...

Authenticate users using Laravel's default authentication system, then serve the Vuejs single page application only to logged

Currently working on a Single Page Application using the default Laravel scaffolding: // Setting up basic scaffolding... php artisan ui vue // Implementing login / registration features... php artisan ui vue --auth These commands provide a solid foundati ...

Retrieving URL Parameters in Meteor-React's createContainer

In my React/Meteor application that utilizes react-router, I am attempting to pass the URL parameters (for example, /user/P8HDQMAuapRESoWo6) into createContainer. This function fetches the result of the initial MongoDB query: let user = Meteor.users.findO ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

I am looking for a way to write a function that will emit an event to the parent component when an icon is

I am creating an input element with an icon to show/hide the password. How can I emit an event in the v-icon to notify the parent component when the icon is clicked? Here is my child component BaseInputPassword: <div class="label"> ...

Obtain a PDF file using jsPDF within an iOS Progressive Web Application

For my bachelor thesis, I am working on developing a PWA. One part of the application involves generating PDF reports using jsPDF and saving them with doc.save("filename.pdf"). This feature works flawlessly on desktop browsers and all Android devices I hav ...

Having trouble integrating a custom image upload adapter plugin into ckeditor 5 using vue js?

I have been working on developing a custom image upload plugin for ckrditor5 using Vue js, Inertia, Vite Js, and Laravel. Despite following the documentation closely and implementing the code as per the guidelines, I encountered an error in the console. ap ...

Error message: Cannot bring in JavaScript category. TypeError: "class" does not work as a constructor

I'm encountering a strange problem when trying to import my class into another module. Everything works fine when I import the worker module in my start.js file and run the script smoothly. But, the issue arises when the socket module attempts to impo ...