我有一个关于vue3编码结构的问题,我想知道实现以下目标的最佳方法。
存储库:https://github.com/TraitOtaku/crudapp-vue3
Office.vue:要加载主要的Office视图(页面),从API中获取office数据并存储在office.js(Pinia)中
用于Office数据的CRUD表单的OfficeForm.vue:模板。单击OK按钮将更新数据。I还想在Axios返回成功的情况下触发弹出( to )。
存储由Axios获取的办公数据的office.js:Pinia文件
https://github.com/TraitOtaku/crudapp-vue3/blob/master/src/views/admin-views/team/Office.vue https://github.com/TraitOtaku/crudapp-vue3/blob/master/src/components/layout-ui/form/member/OfficeForm.vue
我使用这个PrimeVue UI库(https://primefaces.org/primevue/toast),并希望从任何组件调用Toast弹出窗口。
目标:我在PrimeVue UI库中在App.vue
上拥有了这个the组件
<template>
<LayoutView></LayoutView>
<!-- POP UP MESSAGE -->
<Toast position="bottom-left" />
</template>
在App.vue <script setup>
中:
const showSuccess = () => {
toast.add({
severity: "success",
summary: "Success Message",
detail: "Message Content",
life: 3000,
});
};
const showError = () => {
toast.add({
severity: "warn",
summary: "Error Occurred",
detail: "Something went wrong",
life: 3000,
});
};
问题:如何从任何子组件调用showSuccess()和showError()?
我的想法1:使用showSuccess()和showError()提供/注入并发送到Pinia存储,并在Axios响应之后调用每个函数。->似乎很难在.js文件中实现inject()。
我的想法2:使用$root$emit调用App.vue的showSuccess()和showError()。->我不知道如何从App.vue文件接收已发送的$root$emit。
我的想法3:储存价值。当Axios返回成功时,createdData = ref(0)和createdData++。在App.vue文件中创建一个监视程序,并在createdData.value更改时调用createdData.value()
注意:我只是不想在Vue应用程序中到处重复这个组件。
请给我建议。谢谢!
发布于 2022-07-18 19:31:09
简单地说,我添加了吐司功能,它起作用了!
import { defineStore } from "pinia";
import { ref, toRaw, inject } from "vue";
import EventService from "@/plugins/EventService";
import { useToast } from "primevue/usetoast";
export const useOfficeStore = defineStore("office", () => {
const toast = useToast();
const data = ref(null);
const getData = () => {
EventService.getOffice()
.then((response) => {
data.value = response.data;
})
.catch((error) => {
console.log("data:" + error);
toast.add({
severity: "warn",
summary: "Network Error",
detail: "Database connection error",
life: 3000,
});
});
};
getData();
const updateData = (formState, id) => {
EventService.updateOffice(id, toRaw(formState))
.then((response) => {
console.log("Office Updated" + response.data);
getData();
toast.add({
severity: "info",
summary: "Data Created",
detail: "Office Data was successfully updated",
life: 3000,
});
})
.catch((error) => {
console.log(error);
getData();
toast.add({
severity: "error",
summary: "Error Occurred",
detail: "Data was not updated",
life: 3000,
});
});
};
return {
data,
getData,
updateData,
};
});
https://stackoverflow.com/questions/73025483
复制相似问题