VueJs 异步加载模板 [英] VueJs Async loading templates

查看:32
本文介绍了VueJs 异步加载模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建我的第一个 VueJs 应用程序,我想异步加载我的模板.在我们的框架中,我们将模板存储在数据库中,这就是原因.它一直在工作,直到我的模板中有一些嵌套的 dom 元素而没有任何数据绑定到它.所以我的 Vuejs 就像:

var app = new Vue({el: '#app',数据: {完成:假,模板:空},渲染:函数(创建元素){如果(!this.template){return createElement('div', '加载中...');} 别的 {返回 this.template();}},安装(){var self = this;$.post('myUrl', {foo:'bar'}, function(response){var tpl = response.data.template;self.template = Vue.compile(tpl).render;})}})

这在我的模板如下时有效:

<p>测试</p>

但是当它是这样的时候:

<p><span>测试</span></p>

我明白了

<块引用>

[Vue 警告]:渲染错误:类型错误:无法读取属性 '0'未定义"(在 < Root > 中找到)

但是当它是这样的时候:

<p v-show="!finish"><span>测试</span></p>

它又开始工作了.

谁能解释一下这里发生了什么?这是正确的做法还是我应该换一种方式?

解决方案

我猜你应该尝试 v-if 而不是 v-show.v-show 所做的是改变 display 属性,无论如何 vue 都在尝试渲染元素.

文档

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?

解决方案

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

这篇关于VueJs 异步加载模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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