javascript - Vue.js:如何在异步组件中加载模板

标签 javascript 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 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/

相关文章:

javascript - 使用 jQuery 增加输入字段值

javascript - 如何重构重复的条件 Vue.js 代码?

vue.js - Vue中如何获取父模板组件

javascript - 如何将 Vue 模板标记移动到方法中?

css - VueJS 转换与 Pug partials

vue.js - 父级在 Vuejs 中监听子级发出事件

vue.js - 如何在 Vue js 组件中使用 Electron API?

javascript - jQuery 计数函数

javascript - 我将如何使用 jquery click 从导航栏中的元素淡出 html 中的旁白部分?

javascript - 寻找将亚马逊数据插入 php 表单的方法