VueJs CLI将html字符串导入/编译到vue



我正在寻找一个解决方案,将我的html字符串导入到我的VueJs组件中,并能够执行html代码中的任何VueJs代码。我使用VueJs(2.5.x(+CLI来运行vue应用程序,在运行几秒钟后,它向API请求检索HTML代码。

HTML代码(导入并点击卡片后,我应该可以更改accessCardId数据(:

<div class="md-card md-theme-default" v-on:click="accessCardId = '5bfc54cf553b485038333ee5'">
<div class="md-card-media">
<img src="/icons/europa.jpg" alt="People" class="icon">
</div>
<div class="md-card-header">
<div class="md-title">Europa</div>
<div class="md-subhead">Every where, you can us...</div>
</div>
</div>

VueJs脚本(在home.vue中(:

<script>
export default {
name: 'Home',
props: {
msg: String
},
data: () => ({
listCards: null,
currentPage: -1,
accessCardId: null
}),
filters: {
shortDescription: description =>
`${description.substring(0, 150)}${description.length > 150 ? '...' : ''}`
},
methods: {
async loadPage() {
await this.$http.get(`${process.env.VUE_APP_SERVER_URL}/icos?token=${process.env.VUE_APP_SERVER_TOKEN}&page=${this.currentPage + 1}`)
.then(async res => {
this.currentPage = this.currentPage + 1;
// res.body === my html code
});
}
}
}
</script>

您可以使用v-html指令,该指令用于呈现不需要任何事件处理或数据绑定的静态html内容,并且根据官方文档:

span的内容将被rawHtml属性的值替换,被解释为纯HTML-数据绑定被忽略。请注意,不能使用v-html来编写模板部分,因为Vue不是一个基于字符串的模板引擎。相反,组件被首选为UI重用和组合的基本单元

另一个解决方案是使用中的包v-runtime-templatehttps://github.com/alexjoverm/v-runtime-template

这可能对您的用例很有用,因为您通常关心这些方法对恶意注入的安全性。

最新更新