我正在从数据库加载数据,该数据库驱动我显示的组件类型

AJAX调用将启动并返回一些数据(如果需要,可以重新构造)

{
  component_type: 'list-item',
  props: {
    name: 'test',
    value: 'some value'
  }
}

这在我的父对象上是可以访问的,一个名为component的变量

在父对象的模板中,我有以下内容

<component :is="component.component_type" ></component>

这可以正常工作,并按预期加载组件.

接下来,我还想将数据对象中的属性添加到此标记中

<component :is="component.component_type" {{ component.props }} ></component>

这不起作用,拒绝写一个包含{{的标签.我认为这是浏览器而不是Vue引发的错误,尽管我不确定.

作为参考,我希望输出实际如下所示:

<component :is="component.component_type" name='test' value='some value' ></component>

我怎样才能把这些财产传进go ?理想情况下,我希望这些数据和我展示的父对象的数据/props 联系在一起,以便它们可以在数据库中轻松更改,UI也会相应更改.

在最坏的情况下,我会在服务器端生成所有这些内容,但我更愿意像目前try 的那样通过ajax来实现.

推荐答案

在这thread个选项之后,我看到了两个选项.

一种方法是传递一个单独的props ,props 本身就是一个对象,并传递其中所有可由子组件使用的相关键值,如下所示:

<component :is="component. component_type"
        :options="component.props"
</component>

提到的另一个解决方案是有一个指令,在这里你传递对象,它会将该对象中的键属性设置为相应的值,你可以在work here中看到这一点.

Vue.directive('props', {
        priority: 3000,
    bind() {

        // set the last component child as the current
        let comp = this.vm.$children[this.vm.$children.length - 1];
        let values = null;
        if(this._scope && this._scope.$eval) {
            values = this._scope.$eval(this.expression);
        } else {
            values = this.vm.$eval(this.expression);
        }
        if(typeof values !== 'object' || values instanceof Array) {
            values = { data: values };
        }

        // apply properties to component data
        for(let key in values) {
            if(values.hasOwnProperty(key)) {
                let hkey = this.hyphenate(key);
                let val = values[key];
                if(typeof val === 'string') {
                    comp.$options.el.setAttribute(hkey, values[key]);
                } else {
                    comp.$options.el.setAttribute(':' + hkey, values[key]);
                }
            }
        }

                console.log(comp.$options.el.outerHTML);
        comp._initState();
    },

    /*
     * Hyphenate a camelCase string.
     */
    hyphenate(str) {
        let hyphenateRE = /([a-z\d])([A-Z])/g;
        return str.replace(hyphenateRE, '$1-$2').toLowerCase();
    }
});

这样使用:

<div class="app">
    <component is="component.component_type" v-props="component.props"></component>
</div>

Vue.js相关问答推荐

Vue 3:插槽属性 - 可以通过 props 传递数据吗?

是否可以将 nuxt3 与类星体框架一起使用

在 vue.js 中添加新类时样式不适用

手动触发对观察到的对象/数组的更新

在 Ajax 函数中访问 Vue.js 组件属性

Vuejs中的条件a href

Webpack 你可能需要一个合适的加载器来处理这个文件类型

在基于 TypeScript 的 Vue 中将 vuex 状态和Mutations绑定到复选框组件属性

如何将 Nuxt.js 更新到最新版本

v-for 中的 VueJS 插槽

更新 vue.js 中的数据属性/对象

错误:vue-loader 要求 @vue/compiler-sfc 存在于依赖树中

Vue更改宽度和内容

在 Vuejs 中计算 DOM 元素之间距离的最佳方法是什么?

动态注册本地 Vue.js 组件

Proxy代理在 Vue 3 的控制台中是什么意思?

在加载数据之前触发mounted方法 - VueJS

如何在 Vue.js 应用程序中正确下载 Excel 文件?

v-if 未在计算(computed)属性上触发

Vue过滤器应该如何使用typescript绑定?