模版字符串
this.code= `
<template><div style="width:100% ; height: 100% ;">{{resultData[0].name}}</div>
</template>
<script>
export default {data() {return {resultData: [{ name: '图幅', value: 20 },]}},mounted(){},methods: {chartClick(params){console.log(params);}}
}
<\/script>`
上述模版字符串自定义
多说一嘴: 如果要根据某个vue去拿模版字符串可通过raw-loader实现
解析
data(){return {html: '',js: '',css: '',}}methods:{buildDom() {this.splitCode()if (this.html === '' || this.js === '') {return;}const common = new Function(this.js)()common.template = this.html//此时common就是vue模版对象了console.log(common);if (this.css !== '') {const styles = document.createElement('style')styles.type = 'text/css'styles.innerHTML = this.cssdocument.getElementsByTagName('head')[0].appendChild(styles)}},splitCode() {const script = this.getSource(this.code, 'script').replace(/export default/,'return ')const style = this.getSource(this.code, 'style')const template =this.getSource(this.code, 'template') this.js = scriptthis.css = stylethis.html = template},getSource(source, type) {const regex = new RegExp(`<${type}[^>]*>`)let openingTag = source.match(regex)if (!openingTag) return ''else openingTag = openingTag[0]return source.slice(source.indexOf(openingTag) + openingTag.length,source.lastIndexOf(`</${type}>`))},}