【问题标题】:VueJs async template/component with placeholder带有占位符的 VueJs 异步模板/组件
【发布时间】:2018-07-18 20:58:49
【问题描述】:

我对 VueJs 还很陌生,所以我还在搞清楚。 由于我们的模板存储在数据库中,我希望我的模板异步加载。对于我的组件,我现在使用组件工厂方法。

var c = Vue.component('my-async-component', function(resolve, reject){ 
  setTimeout(function(){
    resolve({
      template: '<div class="loader">loaded asynchronous: {{ pageName }}</div>',
      data() {
        return {
          pageName: 'my Page'
        }
      }
    })
  },2000)
})

但是在加载时是否可以使用某种占位符?我知道我可以做一些事情但是在那种情况下我需要有一个父组件,我希望它是独立的。

在 Vue 实例上,您可以在渲染函数结束时将其连接到挂载,如下所示:

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;
    })
  }
})

这可以在组件中实现吗?当我有一些嵌套的 div 时,这是否仍然有效(请参阅我的另一个问题:here

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    好的,我想通了。我只需要更好地了解 VUE 指南。 我刚刚关注了advanced async example from the docs,现在我有了一个工作示例。

    所以我有这样的模板:

        <div id="app">
          <my-async-component></my-async-component>
        </div>
    

    然后在我的 JS 中,我将模板声明为:

        var c = Vue.component('my-async-component', function(){
          return {
            component: new Promise(function(resolve, reject){
              // setTimeout to simulate an asynchronous call
              setTimeout(function(){ 
                resolve({
                  template: '<div class="loader">loaded asynchronous</div>'
                })
              },3000)
            }),
            loading: Vue.component('loader', {
              template: '<p>loading...</p>'
            }),
            error: Vue.component('load-error', {
              template: '<p>error loading component</p>'
            }),
            delay: 200,
            timeout: 10000
          }
        })
    
        var vm = new Vue({
          el: '#app'
        });
    

    加载和错误组件也可以是全局注册的组件,便于复用。

    希望我能帮助别人回答我自己的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 2015-12-14
      • 2015-05-10
      • 2015-05-20
      • 2012-09-10
      • 2023-04-03
      相关资源
      最近更新 更多