从外部脚本登录后调用 VueJS 组件

Calling VueJS Components after login from an external script

我有一个 VueJS 程序,我想在其中提供登录名。因此,此登录在多个平台上使用,它是通过外部服务器加载的(参见:mounted)。它被加载,将元素放入 mainlogin-div 创建登录视图,当用户单击登录时,它会向另一台服务器执行 http 登录请求。登录成功后,无论登录成功与否,外部脚本都会调用done(result)或error(result)。

但是现在当然我怎么能回到从那里调用 Vue 的东西呢?我不能只是这样做。$router.push("/coolPath") 或调用一个已定义的方法,如 loggedIn 来敬酒或其他什么...这是如何实现的?

<template>
  <div id="main">

    <div id="mainlogin"></div>

    <script type="application/javascript">
      function done(result){
        console.log(result);

        loggedIn(result, true)
      }
      function error(result) {
        console.log(result)

        loggedIn(result, false)
      }

    </script>
  </div>
</template>


<script>
const Toast = require("@/toast/toast")

export default {
  name: "Login",
  components: {},

  data() {
    return {
      isAuthenticated: false
    }
  },
  beforeMount() {
    let loginScript = document.createElement('script')
    loginScript .setAttribute('src', 'http://**.***.***.***/index_krass.js')
    document.body.appendChild(loginScript )
  },
  methods: {
    loggedIn: function (result, success){
      Toast.toast(result.message, success)
    }
  }
}
</script>

<style>
...
</style>

错误总是“这个”。未定义或 loggedIn(...) 未定义... 可能是 VueJS 需要先加载或相反的某种竞争条件?

而不是模板中的 <script> 块,只需将 window 上的全局函数设置为 arrow functions 即可捕获 Vue 实例上下文:

export default {
  beforeMount() {
    window.done = result => this.loggedIn(result, true)
    window.error = result => this.loggedIn(result, false)
 
    let loginScript = document.createElement("script")
    loginScript.setAttribute("src", ".../index_krass.js")
    document.body.appendChild(loginScript)
  },
  destroyed() {
    window.done = window.error = undefined
  },
}

demo