【发布时间】:2021-02-13 23:24:15
【问题描述】:
在 Vue 应用程序的组件中,以下方法在用户单击表单上的提交按钮后运行:
execute() {
let message = '';
let type = '';
const response = this.actionMode == 'create' ? this.createResource() : this.updateResource(this.data.accountId);
response.then(() => {
message = 'Account ' + this.actionMode + 'd for ' + this.data.name;
type = 'is-success';
})
.catch(e => {
message = 'Account <i>NOT</i> ' + this.actionMode + 'd<br>' + e.message;
type = 'is-danger';
})
.then(() => {
this.displayOutcome(message, type);
this.closeModal();
});
}
同一组件中的displayOutcome() 方法如下所示:
displayOutcome(message, type) {
this.$buefy.toast.open({
duration: type == 'is-danger' ? 10000 : 3500,
position: 'is-bottom',
message: message,
type: type
});
}
代码在组件中运行良好。现在我正在尝试将 displayOutcome() 方法移动到 helpers.js 文件中并导出该函数,以便应用程序中的任何组件都可以导入它。这将集中维护 toast 并防止在需要的每个组件中写入单独的 toast。无论如何,当displayOutcome() 被移动到 helpers.js,然后导入到组件中时,触发函数时控制台中会出现错误:
我怀疑它与引用 Vue 实例有关,所以我尝试了 main.js 文件并更改了它
new Vue({
router,
render: h => h(App),
}).$mount('#app');
到这里
var vm = new Vue({
router,
render: h => h(App),
}).$mount('#app');
然后在 helpers.js 中
export function displayOutcome(message, type) {
// this.$buefy.toast.open({
vm.$buefy.toast.open({
duration: type == 'is-danger' ? 10000 : 3500,
position: 'is-bottom',
message: message,
type: type
});
}
但这导致“编译失败”。错误信息。
是否有可能使 helpers.js 中的displayOutcome() 以某种方式工作?
【问题讨论】: