Webpack构建后使用Vue组件

时间:2019-08-06 13:56:28

标签: vue.js vuejs2

我有一个提供静态HTML页面的CMS。对于该CMS,我想使用Vue开发组件,然后可以在CMS中单独使用它们。 据我了解,Vue是实现此目的的完美解决方案。

随着TypeScript越来越普遍,我想将TypeScript与Babel和Webpack一起使用,因此CLI项目为我提供了一个完美的样板。

运行npm run build时,我的index.html容器在dist文件夹中得到一个<div id="app"></div>。这可能是我在CMS中的根元素/模板,然后只需在其中传递组件即可。

可悲的是,应用程序容器中的所有内容都被渲染了。

我已经在main.ts文件中注册了组件,并删除了行render: (h)=>h(App),但它也替换了我的容器内容。

Main.ts:

import Vue from 'vue';
import App from './App.vue';
import ButtonLink from './components/ButtonLink.vue';

Vue.config.productionTip = false;

// Adding the component to my Vue context
Vue.component('ButtonLink', ButtonLink);

new Vue({
  // render: (h) => h(App),
}).$mount('#app');

dist目录中的index.html摘录:

 <div id=app>
        <ButtonLink href="https://google.com">A link </ButtonLink>
    </div>

链接到完整项目:https://gitlab.com/cedricwe/vue-problem/tree/master

我做错了什么?这有可能吗?

2 个答案:

答案 0 :(得分:0)

您似乎正在使用in-DOM模板而没有运行时编译器,这会产生以下浏览器控制台警告:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

(found in <Root>)

默认情况下,不包括运行时编译器以减小包的大小。您可以在Vue CLI项目中使用项目根目录vue.config.js中的runtimeCompiler标志来启用它:

module.exports = {
  runtimeCompiler: true
}

答案 1 :(得分:0)

您真正想做的是为Vue实例提供一个“安装点”。在这种情况下,我们通常使用el option来代替它:

import Vue from 'vue';
import App from './App.vue';
import ButtonLink from './components/ButtonLink.vue';

Vue.config.productionTip = false;
new Vue({
    el: '#app', // mounts this instance to #app but doesn't render it
    components: {
        ButtonLink // optionally have it local to your instance vs global
    }
});