vue动态渲染后端返回的html模板

vue动态渲染后端返回的vue模板字符串

前言

有这样一个需求,用户自己定义html模板,定义完成后将模板上传至服务器,后端将这个html模板字符串返回给前端,前端动态的将这个模板渲染到页面上
这个需求的要点不是渲染简单的html字符串,而是要将模板字符串中的变量(也就是{{}}中的变量)转化成具体的值一并渲染出来

实现方法

1.引入 vue 用于创建构造器

正常引入vue的方式应该是

 import Vue from 'vue'

但是这种方式可能会引发报错:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

如果出现以上这种报错,请把引入方式更改为:

import Vue from 'vue/dist/vue.esm.js'

2 创建构造器

<template>
	<div id='mount-point'>
	</div>
</template>

import Vue from 'vue/dist/vue.esm.js'
export default {
	data() {
		return {

		}
	},
	created() {
		//假设此字符串是在后端获取的
		let str = '<div><span style="color: red;">{{title}}</span></div>'; 
		// 创建构造器
		var Profile = Vue.extend({
			template: str,
			data: function() {
				return {
					title: ''
				}
			},
			created() {
				this.getData()
			},
			methods: {
			// 模拟请求-获取数据源
			  getData() {
				setTimeout(()=> {
					this.title = '测试标题'
				},2000)
			    }
			 }
		})
		// 创建 Profile 实例,并挂载到一个元素上。
		new Profile().$mount('#mount-point')
	}
}

效果

在这里插入图片描述

  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

雾里桃花

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

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

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

打赏作者

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

抵扣说明:

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

余额充值