9

我们有一个 Vue 应用程序,并希望允许第三方创建插件。我们希望插件以 Vue 单文件组件的形式构建。

在运行时,最终用户会选择一个插件添加到应用程序中。该应用程序将获取纯文本 .vue 文件,即时编译它,并将其显示在应用程序中。

Vue 支持动态和异步组件,但这些组件需要提前编译到应用程序中。我们想做同样的事情,除了动态加载代码。

我怎样才能使这项工作?

这是我到目前为止所得到的:

<template>
  <div>
    The component goes here:
    <component :is="pluginComponent"></component>
  </div>
</template>
<script>
import { parseComponent } from "vue-template-compiler";
export default {
  data() {
    return {
      pluginComponent: null
    };
  },
  mounted() {
    // fetch code from some external source here
    let code = "<template><div>hello</div></template>";
    let comp = parseComponent(code);
    this.pluginComponent = comp;
  }
};
</script>

(我修改了构建,因此存在 vue-template-compiler。)

上面的代码会产生这个错误:

[Vue warn]: invalid template option:[object Object]
found in
---> <Anonymous>
       <Pages/plugin/PluginId.vue> at pages/plugin/_plugin_id.vue
         <Nuxt>
           <Layouts/default.vue> at layouts/default.vue
             <Root> instrument.js:110
    instrumentConsole instrument.js:110
    VueJS 15
TypeError: "vnode is null"
    VueJS 14
instrument.js:110

我猜想无论 parseComponent() 产生什么都不<component>是我们想要的。

4

1 回答 1

2

我猜想parseComponent()产生的不是我<component>想要的

我会说是的,因为它似乎没有编译为任何render函数。

文档中所述,vue-template-compiler用于运行时编译。在大多数情况下,您应该将它与vue-loader.

我怎样才能使这项工作?

您可能希望使用Vue.compile它,因为它允许您将模板字符串编译成render函数;然后您可以将其绑定到异步或动态组件的对象。

但是请注意,这仅在完整构建中可用,它比仅运行时构建对应物重约 30%。阅读更多关于Runtime + Compiler vs. Runtime-only 的内容。

考虑到这一点,由于您没有在问题中提及您正在使用哪个捆绑程序,我将假设 Webpack 与 Vue-CLI,以及您将如何配置vue别名(作为导入时的参考点)。

验证你设置的 Vue“别名”

在您的控制台中(从项目的根目录),运行:

vue inspect resolve.alias.vue$

如果这导致出现“vue/dist/vue.runtime.esm.js”(默认情况下应该是),那么很明显我们需要更改这部分。

配置它

现在,由于使用 维护内部 webpack 配置webpack-chain,我们将像这样配置/重置别名:

module.exports = {
  chainWebpack: config => {
    config.resolve.alias
      .set('vue$', 'vue/dist/vue.esm.js')
  }
}

查看不同构建的解释

使用它

此时,您需要做的就是将“动态”模板传递给compile函数,<template>但不包括标签。

import Vue from 'vue';

export default {
  mounted() {
    // fetch code from some external source here
    let code = '<div>hello</div>';
    let comp = Vue.compile(code);

    this.pluginComponent = comp;
  }
}
<template>
  <div>
    The component goes here:
    <component :is="pluginComponent"></component>
  </div>
</template>
于 2020-05-27T05:21:59.140 回答