2017-07-25 55 views
2

我是的全新品牌,我试图设置一个简单的网站。每个页面都有一个组件(关于我们,联系我们等)。Vue.js:如何在异步组件中加载模板

这是我的工作起点

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加载)

+0

放入回调'resolve'呼叫:'如果(r.success){决心({模板:r.data})}' – thanksd

回答

1

您需要将您的解决方案移动到ajax回调。使用这种construction_

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!") 
     } 
    }); 
}); 
0

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