如何在重定向到另一个页面(如表单提交)时在 vuejs 中添加 bootstrap 5 toast

How can I add bootstrap 5 toast in vuejs while redirecting to another page (like form submission)

如何在 vuejs 中添加 bootstrap5 toast 重定向 到另一页。 例如:当我们提交表单并重定向到另一个页面时,在该页面上我想要祝酒词你的

form is submitted.

您可以使用 eventbus or Vuex. Below is simple example with vuex. Here 正在使用 Vue3 进行演示。

const { Toast } = bootstrap

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

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/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/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>