1

我们正在设计一个插件架构,并且很好奇是否有办法允许通过 URL 将 3rd 方插件作为 Vue 组件包含在内。

如何从远程 url 导入 vue 文件?例如,我试图按照 Alex Jover Morales 的方法来导入异步组件Async vue.js components。在这种方法中,当用户单击“导入插件”按钮时,应该会出现一个从 url 导入的 vue 组件。我在 github 页面上发布了我想导入的 vue 组件。

该应用程序无法解析该网址。为什么不?我必须做些什么来解决这个问题? 导入错误

这是我正在导入的 vue 组件的代码...

  <div v-if="showPlugin">
    <MassEmailerPlugin>
    </MassEmailerPlugin>
    <button @click.prevent="addPlugin">Add Plugin</button>
  </div>
</template>

<style>
</style>

<script>
export default {
  name: "Plugins",
  components: {   
    MassEmailerPlugin: () => import('https://github.com/gideongrossmanHome/test-vuejs-plugin/blob/master/index.html')
  },

  data() {
    return {
      showPlugin: false
    }

  },

  methods: {
    addPlugin() {
      this.showPlugin = true;
      console.log("showing plugin");
    }
  }
};
</script>

这是我要导入的组件...

<template>
    <div>
        Plugin from url
    </div>
</template>

<script>
export default {
    name: "MassEmailerPlugin"
}
</script>
4

2 回答 2

0

您当前的实现存在一些问题:

  • 您拥有的动态import声明是针对 GitHub.com 网页的,而不是组件本身的代码。如果你只想要代码,你应该点击页面右上角的“Raw”按钮,它会给你一个这样的 URL:https ://raw.githubusercontent.com/gideongrossmanHome/test-vuejs-plugin/主/index.html
  • 你的 Vue 组件应该声明为.vueand not .html
  • 即使这样,您也需要以某种方式从.vue文件中编译 Vue 组件并将其注册到 Vue 实例中以使其工作。

如果你真的想使用来自远程 URL 的组件,你可以做的是使用 webpack 将它们编译为 JS 代码,然后像在你的代码中那样动态导入。但是,允许外部 JS 在您自己的站点上运行是非常危险的,并且可能会使您面临 XSS 攻击。

相反,如果您正在处理将在内部使用的东西,我建议您看看能够将您的插件导出为 npm 包。这样,您可以在需要时导入它(仍然适用于动态导入),并且可以很好地打包为一个工作和可重用的包。这是有关如何执行此操作的基本指南,但您可能需要更多研究:https ://vuejs.org/v2/cookbook/packaging-sfc-for-npm.html 。

于 2019-05-29T03:13:10.427 回答
0

I agree with the previous comment. I think the main thing is that the code you are importing may need to be compiled to plain ol' JavaScript before you can import it (and you also need to import the actual source, not the GitHub page).

Another recommendation I would make is to simply copy the component you are trying to import into your project somewhere (maybe like /src/vendor/Component.vue for third party things) and then you can dynamically import it into your project like any other component. This approach has the benefit of not requiring you to compile the third party component since it will become part of your source code.

And if copying the code into your repo is not an option, perhaps this third party plugin is available via npm install? If it's on NPM, you could install it from there, and if it's just on GitHub, you might still be able to install it. Then still go for dynamic import.

Hope that helps.

于 2019-05-29T04:48:24.670 回答