【问题标题】:Vue.js: how to load a template inside an async componentVue.js:如何在异步组件中加载模板
【发布时间】:2017-07-25 19:34:36
【问题描述】:

我是 的新手,我正在尝试用它建立一个简单的网站。每个页面都有一个组件(关于我们、联系我们等)。

这是我的工作起点

Vue.component('about-us', {
    template: '<div>...lots of markup...</div>'
});

我想将该代码转换为异步工作的代码。尝试遵循文档,这是我的代码:

Vue.component('about-us', function(resolve, reject){
    let template_string = '';

    // Load the template with ajax
    $.post(ajax_url, {'action': 'get_about_page'}, function(r){
        r = JSON.parse(r);

        // Save the template string
        if( r.success ) {
            template_string = r.data;
        }
    });

    // Resolve callback for Vue
    resolve({
        template: template_string
    });
});

我得到的错误是:

[Vue 警告]:无法挂载组件:模板或渲染函数没有 定义。在 ---> 匿名根中找到

问题:我的方法错了吗?是语法问题吗?我不确定我是否走在正确的道路上。 (是的,我已经加载了 jQuery)

【问题讨论】:

  • resolve 调用放入回调中:if (r.success) { resolve({ template: r.data }) }

标签: vuejs javascript vue.js


【解决方案1】:

您需要将您的解析移动到 ajax 回调中。

Vue.component('about-us', function(resolve, reject){
    // Load the template with ajax
    $.post(ajax_url, {'action': 'get_about_page'}, function(r){
        r = JSON.parse(r);

        // Save the template string
        if( r.success ) {
            // Resolve callback for Vue
            resolve({
              template: r.data
            });
        } else {
          reject("Unable to define component!")
        }
    });
});

【讨论】:

    【解决方案2】:

    我正在使用这个结构_

    Vue.component('about-us', function (resolve, reject) {
      $.post('ajax_url', {'action': 'get_about_page'}, 'html')
       .done(function (data) {
         resolve({template: data})
       })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2019-06-08
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      相关资源
      最近更新 更多