VueJS - 如何使用 ajax 调用的结果动态初始化模板

2022-01-24 00:00:00 javascript vue.js mvvm coffeescript

我想为 VueJS 组件动态加载 template.我想使用 jQuery 进行 AJAX 调用,无论服务器返回什么都应该是 VueJS 组件的 template.这是删除了 AJAX 调用的代码的简化版本,因为它与数据的来源无关:

I want to load the template for a VueJS component dynamically. I'd like to make an AJAX call using jQuery, and whatever the server returns should be the template of the VueJS component. Here's a simplified version of the code with the AJAX call removed since it's irrelevant where the data is coming from:

BoardFeed = Vue.extend
    template: '<div>This should be replaced</div>'
    data: ->
            return items: null
    created: ->
        @template = "<div>Template returned from server, what I really want</div>"

在上面的示例中,我使用了 created 钩子,我认为这是适合这个,但新模板永远不会渲染,只会渲染旧模板.

In the above example I'm using the created hook which I thought would be suitable for this, but the newer template is never rendered, only the older one.

有可能实现吗?

推荐答案

您可以在模板中使用 v-partial.当你加载了部分,你可以通过 Vue.partial() 注册它.然后替换 {{ partial }} 值,从而呈现新的部分.

You could use v-partial in your template. And when you've loaded the partial, you can register it via Vue.partial(). The {{ partial }} value is then replaced, thus rendering the new partial.

BoardFeed = Vue.extend
    template: '<div v-partial="{{ partial }}">This should be replaced</div>'
    partials: {"beforeLoad": "<div>This should be replaced</div>"}
    data: ->
            return {items: null, partial: "beforeLoad"}
    created: ->
        Vue.partial("afterLoad", "<div>Template returned from server, what I really want</div>")
        @partial = "afterLoad"

(请原谅任何咖啡脚本错误,我不是很熟悉)

(and excuse any coffee-script errors, I'm not very familiar with it)

相关文章