VueJS - 如何使用ajax调用的结果动态初始化模板 [英] VueJS - How to initialize a template dynamically with the result of an ajax call

查看:1189
本文介绍了VueJS - 如何使用ajax调用的结果动态初始化模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态加载VueJS组件的模板。我想使用jQuery调用AJAX,并且服务器返回的应该是VueJS组件的模板。这里是一个简化的代码,其中删除了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 hook,我认为这将适合这个,但是更新的模板从来不渲染,只有旧的。

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.

有可能实现这一点吗?

Is it possible to achieve this?

推荐答案

您可以在模板中使用 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)

这篇关于VueJS - 如何使用ajax调用的结果动态初始化模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆