在vue中若是要渲染字符串形式的標籤,vue 提供了 v-html 指令,能夠很方便的渲染出來。可是若是這個標籤是一個組件,或者element-ui 的組件時,就不能解析出來了,由於v-html 只能解析原生的屬性。css
那麼就要使用jsx渲染來解析html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- 引入樣式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> </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>
固然在開發過程當中確定不會像上面那麼些,將採用如下方法:vue
<template> <div :class="$options.name"> <cmp :html="el"></cmp> </div> </template> <script> import Vue from 'vue'; import AudioPlay from '@/components/media/audioPlay'; Vue.component('audio-play', AudioPlay); export default { name: 'audio', data() { return { el: '<div><audio-play></audio-play><p>hello world</p></div>' }; }, components: { cmp: { props: { html: String }, render(h) { const com = Vue.extend({ template: this.html }) return h(com, {}) } } }, }; </script> <style lang="sass" scoped> </style>
參考社區回答 https://segmentfault.com/q/1010000015734369element-ui