VueJS - How to initialize a template dynamically w

2019-04-02 12:26发布

问题:

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>"

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?

回答1:

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)