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

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

问题描述

我想为 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)

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

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