如何将Vue.js组件作为对象存储在数据库中?

时间:2018-08-30 14:23:30

标签: javascript node.js vue.js

我想在数据库中存储vuejs组件(例如,通常在全新的vue安装中通常具有的HelloWorld组件)。我可以使用某种序列化过程/程序包来序列化vuejs组件吗?谢谢:)

2 个答案:

答案 0 :(得分:1)

Vue组件只是文本,因此它们可以按原样进入数据库。 请不要这样做。数据库用于数据!代码版本控制系统和部署工具用于代码。在代码和数据方面,没有LGBT之类的东西。

答案 1 :(得分:0)

使用Vue <component/>标签创建一个占位符。在我们从服务器(例如数据库)中获取模块时,它将允许一个null :is属性。

<component id="app" :is="componentName"></component> <!-- null for now -->

现在让我们从服务器上的数据库中获取模块。就我而言,我使用映射到.mjs的Spring控制器从数据库中获取Javascript,并以text / javascript mime类型返回它。

export default {
    data: {
        componentName: null
    },
    async beforeMount() {
        const module = await import('/components/random-component.mjs')
        const rawComponent = module.default;
        const componentName = rawComponent.name;
        Vue.component(componentName, rawComponent);
        this.componentName = componentName;
    },
}

上面的代码通过动态导入获取ES6模块,然后使用Vue.component()调用对其进行注册。

以及模块的内容:

export default {
    name: "page",
    data() {
        return {
            message: "Hello World",
        }
    },
    template: "<h1>{{message}}</h1>"
}

Vue.ks官方文档中的更多信息:https://vuejs.org/v2/guide/components-registration.html