Laravel和VUE 3中的路由器推播和提示通知問題
P粉464208937
P粉464208937 2024-01-16 11:11:12
0
1
525

我有一個問題,當使用 router.push 在元件之間切換時,不會顯示 Toast 通知。我有用戶編輯視圖,我想要做的是在編輯後重定向到用戶的個人資料並立即顯示 toast 通知。

粗略地說,我有以下內容:

Routes.js

#
import { createRouter, createWebHistory } from 'vue-router';

//Modules
import DashboardIndex from './components/modules/dashboard';
//Users
import UsersIndex from './components/modules/users';
import UsersCreate from './components/modules/users/create';
import UsersEdit from './components/modules/users/edit';
import UsersView from './components/modules/users/view';


export default new createRouter({
    history: createWebHistory(),
    routes: [
        { path: '/', name: 'dashboard.index', component: DashboardIndex },
        { path: '/users',  name: 'users.index', component: UsersIndex},
        { path: '/user/create',  name: 'user.create', component: UsersCreate},
        { path: '/user/edit/:id',  name: 'user.edit',  props: true, component: UsersEdit},
        { path: '/user/:id',  name: 'user.view',  props: true, component: UsersView},
    

    ]
})

可組合/user.js

import axios from 'axios';
import { useRouter } from 'vue-router'
import { useToast } from 'primevue/usetoast';

export default function useUsers() {

    const users = ref([])
    const user = ref([])
    const errors = ref([])
    const router = useRouter()
    const toast = useToast()
    /**
     * 
     * All Users
     * 
     */
    const getUsers = async () => {
       const response = await axios.get('/admin/users')
       users.value = response.data
    }
    /**
     * 
     * Create User
     * 
     */
    const storeUser = async (data) => {
        try {
            let response = await axios.post('/admin/user', data)
            await router.push({ name: 'user.view',  params: { id: response.data.id } })
        } catch (e) {
            if (e.response.status === 422) {
                errors.value = e.response.data.errors    
            }
        }
 
    }
    /**
     * 
     * Create User
     * 
     */
     const updateUser = async (id) => {
        try {
            //this.showToast = true;
            let response = await axios.put(`/admin/user/${id}`, user.value)
            router.push({ name: 'user.view',  params: { id: response.data.id } })
            toast.add({severity:'success', summary: 'Éxito', detail: 'El Usuario ha sido modificado', life: 3000})
        } catch (e) {
            if (e.response.status === 422) {
                errors.value = e.response.data.errors    
            }
        }

    }
     /**
     * 
     * View User
     * 
     */
    const showUser = async (id) => {
        let response = await axios.get(`/admin/user/${id}`)
        user.value = response.data

    }
 
    /**
     * 
     * Delete User
     * 
     */
    const destroyUser = async (id) => {
        await axios.delete(`/admin/user/${id}`)
    }
     

    return {errors, users, user, getUsers, storeUser, updateUser, showUser, destroyUser}

}

View.vue

#
<template>
  <div class="container-fluid">
    <Toast position="bottom-right"/>
USER PROFILE
                </div>
</template>
<script>
    import useUsers from '../../../composables/users'
    import { onMounted } from 'vue';

    export default {
        props: {
            id: { required: true }
        },
     
        setup(props) {

            const { user, showUser } = useUsers();

            const showUserMounted =  async () => {
                await showUser(props.id)
            }
            onMounted(showUserMounted)
           
            return { user }
        }
    }
    </script>

重要的事實,我正在使用 Prime VUE。

此外,我還評論說,當我轉到toast.add({severity:'success', Summary: 'Success',detail: 'The User has been Modified', life: 3000}) 在showUser 中,可以很好地顯示toast 訊息。

我認為我需要的是一個標誌,它可以更改updateUser 方法中的值(例如showToast = true),並從showUser 方法驗證它是否為true,如果是,則執行toast.add,但我不'最後不知道該怎麼做。

非常感謝。

P粉464208937
P粉464208937

全部回覆(1)
P粉926174288

使用 pinia 進行商店提醒,您可以存取整個應用程式的提醒:

import { defineStore } from "pinia";
import { useToast } from "primevue/usetoast";

export const useAlertStore = defineStore({
    id: "alert",
    state: () => ({
        toast: useToast(),
    }),
    actions: {
        success(title, message) {
            this.toast.add({
                severity: "success",
                summary: title,
                detail: message,
                life: 3000,
            });
        },
        info(title, message) {
            this.toast.add({
                severity: "info",
                summary: title,
                detail: message,
                life: 3000,
            });
        },
        warn(title, message) {
            this.toast.add({
                severity: "warn",
                summary: title,
                detail: message,
                life: 3000,
            });
        },
        error(title, message) {
            this.toast.add({
                severity: "error",
                summary: title,
                detail: message,
                life: 3000,
            });
        },
    },
});

然後例如我的登入功能:

const alert = useAlertStore();

async function login() {
    const authStore = useAuthStore();
    await authStore.login(formData.email, formData.password);
    alert.success(
        t("alerts.loginTitle"),
        t("alerts.user") + `${authStore.user.name} ` + t("alerts.loginMessage")
    );
}

最後將 Toast 元件加入您的 App.vue 檔案:

<template>
    <Toast />
    <router-view />
</template>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板