在vue开发中,我们经常碰到一些vue模板解析的问题,用户在代码编辑器中用vue写的代码,我们从里面拿到的是一个字符串,这个时候,我们就需要把这个字符串解析成我们需要的内容
主要源码如下:
<template>
<div>
<div>vue代码解析</div>
<!-- 组件渲染 -->
<component :is="comp" />
</div>
</template>
<script type="text/javascript">
import Vue from 'vue'
import {js} from './js'
const compiler = require('vue-template-compiler')
export default {
data () {
return {
code: js,
comp: 'test-template'
}
},
created () {
this.handleUpdate()
},
methods: {
// 组件更新渲染
handleUpdate () {
let a = compiler.parseComponent(this.code)
// 样式添加
if (a.styles && a.styles.length > 0) {
let s = document.createElement('style')
s.innerHTML = a.styles[0].content
document.body.append(s)
}
// 脚本添加
let js = {}
if (a.script) {
let script = a.script.content.split('export default')[1]
let last = script.lastIndexOf('}')
script = script.substring(0, last + 1)
if (script) {
js = eval('(' + script + ')')
}
console.log(js)
}
// 组件注册
Vue.component(this.comp, {
template: a.template.content,
...js
})
}
}
}
</script>
js文件代码如下:
export const js = `<template>
<div @click="handleClick">测试点击</div>
</template>
<script>
export default {
methods: {
handleClick () {
alert('点击事件')
}
}
}
</script>
`