gpt4 book ai didi

compilation - 如何在Vue中编译从外部api加载的模板

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:29 25 4
gpt4 key购买 nike

我有一个非 SPA 网络应用程序,它有 Vue组件,效果很好。但是,我正在寻找一种方法来加载包含 Vue 的 HTML通过外部 API。

因此,我只需调用电话 /ajax/dialogbox/client/add返回包含 Vue 的 HTML组件,例如:

<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>

但显然<my-component></my-component>什么都不做。在 Angular 1我用的是 $compile在输出之前编译 HTML 的服务。

有没有办法在 Vue 中做同样的事情? ?

最佳答案

有一个compile function在 Vue 中可用,它编译模板以呈现函数。使用编译后的函数需要比您提供的更多的细节(例如,如果您需要将返回的模板与数据一起使用),但这里有一个示例。

console.clear()

Vue.component("my-component",{
template: `<h1>My Component</h1>`
})

const template = `
<div>
<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>
</div>
`

new Vue({
el: "#app",
data:{
compiled: null
},
mounted(){
setTimeout(() => {
this.compiled = Vue.compile(template)
}, 500)

}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
<component :is="compiled"></component>
</div>

请注意,在示例中,我将您的示例模板包装在 div 标记中。 Vue 要求 Vue 或组件只有一个根元素。

关于compilation - 如何在Vue中编译从外部api加载的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44874699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com