Vue模板字符串的使用,【html标签、Element-uivue template模板渲染】

技术
Vue父子组件传值
Vue render函数的引用
Vue.extend的使用
Vue v-html的引用
背景
业务需在web端回显DOm结构的报告预览,现主要针对element组件元素渲染的代码解析

在引入正题之前,我们先来关注一下这个问题,

关于在vue 中 html标签的渲染与使用[v-html]

现简述用法:

 <div class="content" v-html="rawHtml | htmlFilter"></div>

需将转义过的html代码通过vue的filter(过滤器)转义成为普通html代码,本例中添加了名为htmlFilter的过滤器:

filters: {
        unescape:function (html) {
            return html
                .replace(html ? /&(?!#?\w+;)/g : /&/g, '&')
                .replace(/</g, "<")
                .replace(/>/g, ">")
                .replace(/"/g, "\"")
                .replace(/'/g, "\'");
        }
    }

接下来,我们进入正题:

关于在vue 中element组件标签模板渲染与使用

总体结构为:父组件->子组件[此为需要的渲染的element结构标签]

此业务为前后端联调,后端负责返回需要渲染的模板字符串格式,如下图所示:

templateHtml: `<el-form
      :model="{ type: '' }"
      :rules="{ type: [{ required: true, trigger: '' }] }"
    >
      <el-form-item label="活动性质" prop="type">
        <el-checkbox :value="true" label="美食/餐厅线上活动"></el-checkbox>
        <el-checkbox label="地推活动"></el-checkbox>
        <el-checkbox label="线下主题活动"></el-checkbox>
        <el-checkbox label="单纯品牌曝光"></el-checkbox>
      </el-form-item>
    </el-form>`,

前后采用template替代模板字符串直接渲染在v-html中未果,随后查询资料得知可以使用render,Vue.extend挂载,jsx渲染等技术,本例将主要介绍前两者:

首先,在引入子组件中申明需要渲染的模板templateHtml:

<mySlot :html="templateHtml"></mySlot>

随后使用render函数渲染,最后实现模板的动态赋值,代码块如下:

import Vue from "vue";
  export default {
    name: "RequireHtml",
    components: {
      mySlot: {
        // template: `<div>{{myMessage}}</div>`,
        // 在 JavaScript 中使用 camelCase
        props: {
          html: String,
        },
        render(h) {
          const com = Vue.extend({
            template: this.html,
          });
          return h(com, {});
        },
      },
    },
    data() {
      return {
        isShow: undefined,
        templateHtml: `<div></div>`,
      };
    },
    methods: {
      getList(html) {
        this.templateHtml = html;
      },
    }, 
  };

备注:这里的getList方法用于父级组件的字符模板传值

此致
Kyle

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Calmness_7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值