VueJs Async loading templates

2019-08-02 15:35发布

问题:

I Am building my first VueJs App and I want to asynchronous load my template. In our framework we have our templates stored in a database, that's why. It is working until I have some nested dom-elements in my template without any data bound to it. So my my Vuejs is like:

var app = new Vue({
  el: '#app',
  data: {
    finish: false,
    template: null
  },
  render: function(createElement) {
    if (!this.template) {
      return createElement('div', 'loading...');
    } else {
      return this.template();
    }
  },
  mounted() {
    var self = this;
    $.post('myUrl', {foo:'bar'}, function(response){
      var tpl = response.data.template;
      self.template = Vue.compile(tpl).render;
    })
  }
})

This is working when my template is like:

<div v-show="!finish">
  <p>Test</p>
</div>

But when it's like this:

<div v-show="!finish">
  <p>
    <span>Test</span>    
  </p>
</div>

I get

[Vue warn]: Error in render: "TypeError: Cannot read property '0' of undefined" (found in < Root >)

But when it's like this:

<div v-show="!finish">
  <p v-show="!finish">
    <span>Test</span>    
  </p>
</div>

It's working again.

Can anyone explain what is happening here? And is this the right way to do it or should I do it an other way?

回答1:

My guess would be that you should try v-if instead of v-show. What v-show does is changing display property, vue is trying to render the element anyway.

docs