【问题标题】:VueJs Call plugin from .js file来自 .js 文件的 VueJs 调用插件
【发布时间】:2021-03-18 13:10:45
【问题描述】:

我需要你更深入地了解我如何使用 vueJS。

我的应用

我有一个Login.vue,它正在调用一个函数logUser() from UserActions.js,它正在调用我的AxiosFacade.js' function postRequest()

我使用插件以createApp(App).use(Toaster).mount('#app') 显示烤面包机信息并使用this.$toast.show(`Default Toast Message`); 调用我的烤面包机

我想做的事

我想从 AxiosFacade.js 中我的 axios 调用的 catch 部分调用我的函数 this.$toast.show

类似:

return axios.post(`${serv}/${ressource}`,
    {
        data: params,
    },
    {headers: {'Authorization': 'Bearer ' + token}})
    .then((response) => response = response.data)
    .catch((err) => {
        this.$toast.error(err.response.data.message);
        throw err.response.data.message
    })

但我不太明白如何从 .js 和 .vue 文件中创建链接

PS:下一步将是拥有我自己的 Toaster.vue 组件,并在我的 AxiosFacade.js 中显示/隐藏它,如果你也有这方面的提示:)

谢谢!

【问题讨论】:

  • this 不能在自定义 js 文件中工作,因为它不是 vue 参考
  • 是的,我从控制台中看到的undefined 看到了这个,但我不知道如何访问我的函数
  • 需要从main.js文件中导入vue
  • 很抱歉,我可能需要更多信息才能完成所有流程。我在 main.js 中 import Vue from 'vue',但是如何在另一个文件中调用我的函数?

标签: javascript vue.js plugins toast


【解决方案1】:

如果删除 axios 函数的 catch 部分会怎样

return axios.post(`${serv}/${ressource}`,
{
    data: params,
},
{headers: {'Authorization': 'Bearer ' + token}})
.then((response) => response = response.data)

在你想展示吐司的地方抓住它。登录.vue:

function logUser () {
  return postRequest()
    .then(responseData => {
      //do your stuff
    })
    .catch((err) => {
      this.$toast.error(err.response.data.message)
      throw err.response.data.message
    })
}

更新:

解决方案实际上非常简单。您只需要将 this 需要作为 vue 实例的方法添加到您的组件。

参见以下示例:

访问VueInstance.js:

export function compare(vueInstance) {
  return this === vueInstance
}

MyComponent.vue:

导入函数

import { compare } from "./accessVueInstance"

将函数添加到您的组件中:

如果你使用类组件:

export default class MyComponent extends Vue {
  compare = compare

  created() {
    console.log(this.compare(this)) //will log true
  }
  //your stuff
}

其他:

methods: {
  compare
},
created() {
  console.log(this.compare(this)) //will log true
}

vue docs

Vue 自动为方法绑定 this 值,以便它始终 引用组件实例。

看到它在行动codesandbox.io

【讨论】:

  • 这是我的实际解决方案但是行为总是相同的“如果错误则显示后端返回的错误”我想重构我的代码以将此重复代码放在 Axios 外观中并清理我的代码
  • 您可以尝试将 AxiosFacade.js 设为 vue plugin 或者您需要将 vue 实例传递给 AxiosFacade.js。如果您向我展示 AxiosFacade.js 的外观,我可以为您提供帮助。
  • 我已经放弃了 AxiosFacade.js 和 UserAction.js 作为答案 :) 谢谢你的帮助
猜你喜欢
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 2020-10-25
  • 1970-01-01
相关资源
最近更新 更多