在 Vue 中进行回调

Make callback in Vue

我的 vue 小部件是这样工作的。 我使用 https://github.com/karol-f/vue-custom-element 将小部件嵌入到任何网页。

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Foo Page</title>
  </head>

  <body>
    <vue-widget>...</vue-widget>
    <script type="text/javascript" src="/js/app.js"></script>
  </body>
</html>

我的任务是在我的应用程序中创建可以在外部触发的回调函数 <vue-widget>...</vue-widget>。 我试了一下,它不起作用,我不知道为什么

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Foo Page</title>
  </head>

  <body>
    <vue-widget>...</vue-widget>
    <script type="text/javascript" src="/js/app.js"></script>
    <script>
      vueWidget_onInitCallback = function() {
        console.log('foo')
      }
    </script>
  </body>
</html>

App.vue:

methods: {
  someFunction() {
    if (typeof vueWidget_onInitCallback == 'function') {
      vueWidget_onInitCallback();
    }
  },
},
mounted() {
  this.someFunction()
}

好的,我明白了。

index.html

<script>
function vueWidget_onInitCallback () {
  console.log('plugin initiated');
}
</script>

App.vue

methods: {
  someFunction() {
    function onInit(callback) {
      if (callback && typeof(callback) == "function") callback();
    }
    onInit(vueWidget_onInitCallback);
  },
},
mounted() {
  this.someFunction()
}

一切正常。