【问题标题】:NuxtJS / Vue.js - Import external componentNuxtJS / Vue.js - 导入外部组件
【发布时间】:2021-06-16 07:27:06
【问题描述】:

我正在尝试将一个小部件/插件/扩展系统添加到我现有的使用 NuxtJS 编写的 web ui 中。我有一个pages/view.vue 单文件组件,我想在其中实现扩展系统。到目前为止,我的想法是将组件动态加载到通过查询参数指示的单文件组件中,例如/view?extension=example-a.

想法 1

到目前为止,我能找到的最好的东西是这样的:Include external javascript file in a nuxt.js page。我只是不确定如何编译他们的组件,因为我尝试从我的示例组件构建 webpack 资源,但最终无法像上面的示例那样导入它。这是错误消息[Vue warn]: Unknown custom element: <example-a> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

想法 2

我想我可以用http-vue-loader 来做,但我不知道从哪里开始

想法 3

也许我想得太远了,甚至还有更简单的解决方案。

【问题讨论】:

    标签: javascript vue.js webpack nuxt.js


    【解决方案1】:

    您需要将所有组件直接加载到代码中。然后你可以从this.$route.query.extension中的url找到你的参数(如果你使用vue-router),然后通过<component :is="..."/>加载你想要的组件,放入'is'你想要的组件。

    <template>
      <div>
        <component :is="loadedComponent" v-if="loadedComponent !== null"/>
      </div>
    </template>
    <script>
      import exampleA from "./exampleA.vue";
      import exampleB from "./exampleB.vue";
    
      export default {
        data(){
          return {components:{'example-a':exampleA , 'example-b':exampleB }}
        },
        computed:{
          loadedComponent(){
            return this.components[this.$route.query.extension] ?? null;
          }
        }
      }
    </script>
    

    【讨论】:

    • &lt;component :is="..."/&gt; 很有趣!如果我不知道有多少组件怎么办?更好的说法是,假设我交付了一个高效、编译的 Nuxt 项目,并且我想让用户能够添加 n 组件,但总是只将一个加载到页面中?当然我需要做类似的事情,比如通过script 导入一个javascript库。
    • 如果你想编译你的项目然后加载额外的组件 - 这很困难,因为每个组件都需要编译,所以我们需要知道你编译你的项目的方式,如何你想编译组件以及如何交付它。如果您只想获得更快的加载时间,但您的所有组件都在编译时,您可以使用异步导入。
    猜你喜欢
    • 2018-06-17
    • 2017-11-08
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多