我是 vuejs 的新手我正在尝试用它建立一个简单的网站。每个页面都有一个组件(关于我们、联系我们等)。
这是我工作的起点
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 warn]: Failed to mount component: template or render function not defined. found in ---> Anonymous Root
问题:我的方法有错吗?这是语法问题吗?我不确定我是否走在正确的道路上。 (是的,我加载了 jQuery)
最佳答案
您需要将您的决心转移到 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!")
}
});
});
关于javascript - Vue.js:如何在异步组件中加载模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45312078/