鍍金池/ 問答/HTML/ vue 中怎么渲染字符串形式的組件標簽?

vue 中怎么渲染字符串形式的組件標簽?

<div id="app">
    <el-form v-model="form" label-width="100px" class="process-edit-form">
        <el-form-item v-for="item in formParams" :label="item.name + ':'">
            <!-- 這里取 item.html并渲染-->
        </el-form-item>
    </el-form>
</div>

var app = new Vue({
    el: "#app",
    data: {
        button: '<el-button type="primary">按鈕</el-button>',
        form: {
            name: '',
            age: ''
        },
        formParams: [
            {name: '名稱', type: 'name', html: '<el-input v-model.trim="form.name"></el-input>'},
            {name: '年齡', type: 'age', html: '<el-input v-model.trim="form.age"></el-input>'},
        ]
    },
    mounted() {
        this.$nextTick(function () {
            this.$forceUpdate();
        })
    }
})

因為我這個要根據(jù)后臺返回的數(shù)據(jù)來動態(tài)渲染組件,傳給我一個這樣字符串的話,用什么樣的方式可以實現(xiàn)?
用v-html渲染的是這個標簽,而不是組件。

回答
編輯回答
瘋浪

因為我這個要根據(jù)后臺返回的數(shù)據(jù)來動態(tài)渲染組件,傳給我一個這樣字符串的話,用什么樣的方式可以實現(xiàn)?
用v-html渲染的是這個標簽,而不是組件。

2017年5月10日 16:46
編輯回答
玩控
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <!-- 引入樣式 -->
    <link rel="stylesheet" >
</head>

<body>
    <div id="app">
        <el-form v-model="form" label-width="100px" class="process-edit-form">
            <el-form-item v-for="item in formParams" :key="item.name" :label="item.name + ':'">
                <com1 :html="item.html" :form="form"></com1>
                <!-- 這里取 item.html并渲染-->
            </el-form-item>
        </el-form>
        {{ form }}
    </div>
</body>
<!-- 先引入 Vue -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- 引入組件庫 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
    Vue.component('com1', {
        props: {
            html: String,
            form: Object,
        },
        render(h) {
            const com = Vue.extend({
                template: this.html,
                props: {
                    form: Object,
                }
            })

            return h(com, {
                props: {
                    form: this.form
                }
            })
        }
    })

    var app = new Vue({
        el: "#app",
        data: {
            button: '<el-button type="primary">按鈕</el-button>',
            form: {
                name: '',
                age: ''
            },
            formParams: [{
                    name: '名稱',
                    type: 'name',
                    html: '<el-input v-model.trim="form.name"></el-input>'
                },
                {
                    name: '年齡',
                    type: 'age',
                    html: '<el-input v-model.trim="form.age"></el-input>'
                },
            ]
        },
        mounted() {
            this.$nextTick(function () {
                this.$forceUpdate();
            })
        }
    })
</script>

</html>
2017年8月8日 06:36