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



我想在默认的app.js文件中定义一个全局变量或提供/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中提供/注入
setup() {
const toast = useToast();
return { toast };
},
provide: {
toast: this.toast,
},

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

inject: ["toast"]

我得到了错误"注入";吐司;找不到。'

与此答案相关的

(在Vue3中使用筛选器,但不能读取globalProperties(config字段属于根实例,而不属于根组件Vue.createApp(app)返回根实例myApp.mount('#app')返回根组件。您应该在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);
}

最新更新