vue 动态插入渲染html

<template>
  <div>
    <el-row type="flex" justify="center">
      <el-col :span="16">
        <el-card>
          <el-form :v-model="form" ref="form" :rules="rule" label-width="100px">
            <el-form-item label="newHtml" prop="newHtml">
              <el-input v-model="form.newHtml" type="input"/>
            </el-form-item>
            <el-form-item label="newTemplate" prop="newTemplate">
              <el-input v-model="form.newTemplate" type="textarea" :rows="10"/>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="16">
        <el-card header='newHtml' class="vhtml-area">
          <div v-html="form.newHtml">
            <span class="html-class">old word</span>
          </div>
        </el-card>
        <el-card header='newTemplate' class="vhtml-area">
          <div id="demo">
            <!-- <div v-for="item in data" :key="item.name">
              <div>
                <span>{{ item.name }}</span>
                <span>{{ item.age }}</span>
                <span>{{ item.favorite }}</span>
              </div>
            </div>-->
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import Vue from "vue";
export default {
  name: "HelloWorld",
  data() {
    var check = (rule, value, callback) => {
      this.change();
    };
    return {
      form: {
        newHtml: '',
        newTemplate: `1`
      },
      rule: {
        newTemplate: [{ validator: check, trigger: "change" }],
      }
    
    };
  },
  methods: {
    change() {
      var MyComponent = Vue.extend({
        template: `<div>${this.form.newTemplate}</div>`,
        data() {
          return {
            data: [
              {
                name: "张三",
                age: "18",
                favorite: "sleep"
              },
              {
                name: "李四",
                age: "20",
                favorite: "football"
              },
              {
                name: "王二",
                age: "30",
                favorite: "eating"
              },
              {
                name: "麻子",
                age: "40",
                favorite: "honghong"
              }
            ]
          };
        }
      });
      var component = new MyComponent().$mount();
      var dom = document.querySelector("#demo");
      while (dom.hasChildNodes()) {
        dom.removeChild(dom.firstChild);
      }
      dom.appendChild(component.$el);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.vhtml-area {
  min-height: 200px;
  margin-top: 20px;
}
.html-class{
  color: red;
}
</style>

 

posted @ 2019-05-23 11:46  齐大齐  阅读(26722)  评论(0编辑  收藏  举报