【问题标题】:Vue3 - How to invoke a function on App.vue from any components / axios / PiniaVue3 - 如何从任何组件 / axios / Pinia 调用 App.vue 上的函数
【发布时间】:2022-11-10 19:31:23
【问题描述】:

我有一个关于 vue3 编码结构的问题,想知道实现以下目标的最佳方法。

存储库https://github.com/TraitOtaku/crudapp-vue3

办公室.vue: 要加载主要的 Office 视图(页面),从 API 获取 office 数据并存储在 office.js(Pinia) 中

OfficeForm.vue: Office 数据的 CRUD 表单模板。单击确定按钮将更新数据。如果 Axios 返回成功,我还想触发 popup(toast)。

office.js:Pinia 文件,存储 Axios 获取的 office 数据

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 弹出窗口。

目标: 我在 App.vue 上有来自 PrimeVue UI 库的这个 toast 组件

<template>
  <LayoutView></LayoutView>

  <!-- POP UP MESSAGE -->
  <Toast position="bottom-left" />
</template>

在 App.vue &lt;script setup&gt; 中:

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: 使用 Provide/Inject 并将 showSuccess() 和 showError() 发送到 Pinia 存储并在 Axios 响应后调用每个函数。 -> 似乎很难在 .js 文件中实现注入()。

我的想法2: 使用 $root$emit 调用 App.vue 的 showSuccess() 和 showError()。 -> 我不知道如何从 App.vue 文件中接收 emmited $root$emit。

我的想法3: 当 Axios 返回成功时,存储值(例如 createdData = ref(0) )和 createdData++。 在 App.vue 文件中创建一个 watcher 并在 createdData.value 更改时调用 showSuccess()

注意:我只是不想重复这个Vue 应用程序中随处可见的组件。

请指教。 谢谢!

【问题讨论】:

  • showSuccess 等可以只是 Pinia 动作。它适用于全局逻辑。 “似乎很难在 .js 文件中实现注入()” - 为什么?调用 inject() 的代码应该在具有相应 provide() 的 Vue 实例中执行,这是唯一重要的事情。顺便说一句,primevue toast 完全不需要注入,您可以检查它的实现。
  • 谢谢!有效。我需要你的暗示。我很感激。

标签: vue.js axios vuejs3 pinia


【解决方案1】:

只需我添加了 toast 功能,它就起作用了!

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,
  };
});

【讨论】:

    【解决方案2】:

    任何需要在js文件

     // App.vue
    
            <template>
                <Toast />
            </template>
            
            <script>
            import Toast from "primevue/toast";
            
            export default {
              components: {
                Toast: Toast,
              },
            </script>
    
    // store.js
    
            import { useToast } from "primevue/usetoast";
            
            export const StoreExample = defineStore("StoreExample", () => {
              const toast = useToast();
        
              const onActionGetProducts = async () => {
                 return API_EXAMPLE.onApiGetProducts().then(() => {
        
                   toast.add({
                      severity: "success",
                      summary: "Success Message",
                      detail: "Order submitted",
                      life: 3000,
                   });
                 });
              };
        
             return {
               onActionGetProducts,
             };
           });
    

    【讨论】:

      猜你喜欢
      • 2017-09-03
      • 2023-01-20
      • 2022-10-05
      • 2022-08-17
      • 2017-07-26
      • 2022-06-30
      • 2023-02-23
      • 2022-07-10
      • 1970-01-01
      相关资源
      最近更新 更多