3

I have A Vue component which is basically a shorthand for complex HTML markup.

On initial load, Everything works fine.

I am using AJAX to load more of these components onto the page, The problem is that this component, after being loaded with AJAX, doesn't want to get compiled into HTML I only get the un-rendered Vue component like below:

<component><slot>content</slot></component>

I have looked at Vue.compile() and the render function but cannot figure out how to get this working or how to re-render? the components.

Hope that makes sense, Can anyone shed some light on what I should be doing here?

1
  • Can we see some code? Not quite sure what you are doing. Commented Apr 19, 2017 at 15:41

2 Answers 2

5

You should let your data drive the view.

In other words, let's assume you have the following html:

<div id="app">
    <component></component>

    <!-- the following ones are inserted via ajax -->
    <component></component>
    <component></component>
</div>

and js:

var app = new Vue({
  el: '#app',
  data: {
    foo: 'bar',
  }
})

You are probably making the ajax request and inserting manually the <component></component> into the html. That's not the way you should work with Vuejs.

The way you let your data drive the view is, well, creating the needed data:

var app = new Vue({
  el: '#app',
  data: {
    foo: 'bar',
    components: [
        {}, //component related data
        ...
    ]
  },

  components: {
    component,
  },

  ajaxRequest() {
    //this should push into your components array
    // example:
    $.ajax().done(function(data) {
        this.components.push(data);
    })
  }
}) 

In this code, I've added a new array (components) to the data that will store the components I want to render in my view. When I fetch components via ajax I add them to this array. Now, if I change the html to:

<div id="app">
    <component v-for="component in components" data="component">
    </component>
</div>

whenever the components array is updated, Vue will automatically add them to the view.

Sign up to request clarification or add additional context in comments.

1 Comment

you are spot on, I've been going about this the wrong way, thanks for the explanation, should be able to get it working now!
2

Using the functions "extend" and "$mount":

axios.get(url).then((response) => {
    var MyComponent = Vue.extend({
        template: response.data
    })

    var compiled = new MyComponent().$mount()

    $('#div').append(compiled.$el)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.