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

    • 前言
    • 实现方法
      • 1.引入 vue 用于创建构造器
      • 2 创建构造器
    • 效果

前言

有这样一个需求,用户自己定义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')
	}
}

效果

更多推荐

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