首页 > 解决方案 > 在 Javalin 和 Vue 中使用 webjars

问题描述

我知道 Javalin 支持 Vue,我使用它没有问题。它很容易设置,我只需要调用config.enableWebjars()Vue 就可以了,而且非常简单。但是,我想使用与 Javalin 没有深度集成的其他工具。即我想bootstrap-vue用于高级组件。通常,当我通过 npm 和手动配置使用它时,添加对 Vue 的支持也很简单:

import Vue from 'vue'
import { BootstrapVue } from 'bootstrap-vue'

// Install BootstrapVue
Vue.use(BootstrapVue)

但是,这不能直接转换为 Javalin Vue 支持,因为如果我将上述行添加到顶层layout.html

<script>
    import { BootstrapVue } from 'bootstrap-vue'

    var vue = new Vue({el: "#main-vue"});
    Vue.filter("numFormat", function(value) {
        if (value == undefined) return ""
        else return value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
    });
    Vue.config.devtools = true
    Vue.use(BootstrapVue)

</script>

我会得到一个错误:Uncaught SyntaxError: import declarations may only appear at top level of a module

我确信我错过了这一点,所以我将不胜感激任何帮助,如何做到这一点。

标签: bootstrap-vuejavalin

解决方案


我一直在使用 vue 和 Javalin 很短的时间,但我终于明白了,当您使用 Javalin 服务器使用 Vue 时,您处于 ES6 的规则之下,因此要在 .js 扩展名下导入模块,您需要指出您正在使用模块,例如<script type="module">//Imports and code</script>. 现在,如果您需要从 .vue 文件导入,那么您可以使用 http-vue-loader,您可以在此处获取 maven 依赖项:https ://mvnrepository.com/artifact/org.webjars.npm/http-vue -loader,您只需将 替换import { component } from 'module''name of component':httpVueLoader('module route')。一个适用于我从 js 文件导入的小示例:

<script type="module">
  import BarExample from '/componentsjs/BarExample.js'
  import LineExample from '/componentsjs/LineExample.js'
    Vue.component("charts-page", {
        template: "#charts-page",
        components: {
              BarExample,
              LineExample,
            },
            data: () => ({
                dataPoints: null,
                height: 20,
                labelsBar: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                dataBar: [40, 20, 12, 39, 11, 40, 39, 80, 40, 20, 12, 11]
              }
            ),
    });
</script>

还有一个通过 .vue 文件导入的示例:

<script type="module">
Vue.component("main-component-page", {
    template: "#main-component-page",
    components: {
        'app-header': httpVueLoader('/component/header.vue'),
        'app-ninjas': httpVueLoader('/component/ninjas.vue'),
        'app-footer': httpVueLoader('/component/footer.vue')
    },
});
</script>


推荐阅读