如何使用 Laravel 8、Inertia.js 和 Vue3 定义全局变量?

How can i define a global variable with Laravel 8, Inertia.js and Vue3?

我想在默认 app.js 文件中定义全局变量或 provide/inject 或其他方式。

import { createApp, h } from "vue";
import { createInertiaApp } from "@inertiajs/inertia-vue3";
import { InertiaProgress } from "@inertiajs/progress";
import Toast from "vue-toastification";
import "vue-toastification/dist/index.css";
import { useToast } from "vue-toastification";

const appName = window.document.getElementsByTagName("title")[0]?.innerText || "Laravel";
const toast = useToast();

createInertiaApp({
  title: (title) => `${title} - ${appName}`,
  resolve: (name) => require(`./Pages/${name}.vue`),
  setup({ el, app, props, plugin }) {
    return createApp({ render: () => h(app, props) })
      .use(Toast)
      .use(plugin)
      .mixin({ methods: { route } })
      .mount(el);
  },
});

我想将 toast 变量传递给所有其他组件。

以下是我迄今为止尝试过的一些方法:

  1. Vue3 全局属性
createInertiaApp({
  title: (title) => `${title} - ${appName}`,
  resolve: (name) => require(`./Pages/${name}.vue`),
  setup({ el, app, props, plugin }) {
    app.config.globalProperties.$toast = toast; // Cannot read properties of undefined (reading 'globalProperties')

    return createApp({ render: () => h(app, props) })
      .use(Toast)
      .use(plugin)
      .mixin({ methods: { route } })
      .mount(el);
  },
});
  1. 也在AppLayout.vue
  2. 中尝试了Provide/Inject
  setup() {
    const toast = useToast();

    return { toast };
  },

  provide: {
    toast: this.toast,
  },

我试图在其中一个子组件中注入这个。

inject: ["toast"]

我收到错误 'injection "toast" not found.'

与此答案相关 () 配置字段属于 根实例 而不是 根组件 Vue.createApp(app) return root 实例myApp.mount('#app') return root 组件。您应该在 createApp 之后和安装之前配置您的全局属性,如下所示:

import { createApp, h } from "vue";
import { createInertiaApp } from "@inertiajs/inertia-vue3";
import { InertiaProgress } from "@inertiajs/progress";
import Toast from "vue-toastification";
import "vue-toastification/dist/index.css";
import { useToast } from "vue-toastification";

const appName = window.document.getElementsByTagName("title")[0]?.innerText || "Laravel";
const toast = useToast();

createInertiaApp({
  title: (title) => `${title} - ${appName}`,
  resolve: (name) => require(`./Pages/${name}.vue`),
  setup({ el, app, props, plugin }) {
    const myApp = createApp({ render: () => h(app, props) })
      .use(Toast)
      .use(plugin)
      .mixin({ methods: { route } });

    // config global property after createApp and before mount
    myApp.config.globalProperties.$toast = toast;

    myApp.mount(el);
    return myApp;
  },
});

因此您可以在所有组件中使用全局 属性:

mounted() {
  console.log('global toast property: ', this.$toast);
}