我的索引和服务插件具有以下结构:
服务
declare interface Params {
title: string;
description?: string;
type?: string;
duration?: number;
}
export default class ServiceToast {
public toastRef: any; // component
public constructor(modalRef: any) {
this.toastRef = modalRef;
console.log(this.toastRef);
}
public open(params: Params) {
this.toastRef.open(params);
}
}
基本上,我已经创建了一个接收组件的服务,以便它可以轻松地与组件交互。
index.ts:
import _Vue from 'vue';
import Toast from '@/components/_includes/layouts/Toast.vue';
import ServiceToast from './service';
const ToastPlugin = {
install: (Vue: typeof _Vue, options?: any) => {
Vue.mixin({
created() {
Vue.prototype.$toast = new ServiceToast(Toast);
},
});
},
};
export default ToastPlugin;
我在哪里安装插件并使用上面显示的服务。
在这里,我称该插件为对应的Vue.use,但是当我想在任何组件中调用它时:
<a @click="$toast.open({ title: 'Hola mundo' })">Hola, dame click!</a>
我收到以下错误:“ TypeError:this.toastRef.open不是函数”
在el shims-vue-plugin.d.ts中:
/* eslint-disable */
import Vue from 'vue';
import { AxiosInstance } from 'axios';
import 'webpack-env';
import { FieldFlagsBag } from 'vee-validate';
import { SnackbarProgrammatic as Snackbar, DialogProgrammatic as Dialog } from 'buefy';
import ServiceToast from './app-config/toast/service';
declare module 'vue/types/vue' {
interface Vue {
$auth: any;
$axios: AxiosInstance;
veeFields: FieldFlagsBag;
$dialog: typeof Dialog;
$snackbar: typeof Snackbar;
$toast: ServiceToast;
}
}
declare namespace NodeJS {
interface Process extends __WebpackModuleApi.NodeProcess {
server: boolean;
}
}
有谁知道这可能是什么?或由于找不到错误而丢失:/
this.$toast
在任何组件中都不会成为的实例Toast.vue
。这是出口。要拥有一个实际的实例,您需要$mount()
:
import _Vue from 'vue';
// create a class
const ToastClass = _Vue.extend(this.$toast.toastRef);
// get an instance of the class
const instance = new ToastClass();
// mount it
instance.$mount();
// now you have an instance, so you can call any of its methods, i.e:
// instance.open();
// but it's not yet appended to DOM. to append it to the current component:
this.$el.appendChild(instance.$el);
我不知道您要达到什么目的,但是乍看之下,在应用程序的每个组件中都有一个组件实例似乎不是一个好主意。每个Toast实例也将有一个this.$toast
。吐司酒:)
您最好在其中添加一系列吐司,$store
并在应用程序的根元素上附加一个容器,并添加一个普通的
<toast v-for="toast in toasts" />
当烤面包过期时,提交并从状态中删除。
当您想添加另一个时,只需推送一个新的即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句