Skip to content

vue异步组件 #19

@Wscats

Description

@Wscats

构建异步组件

先定义一个外部的xheader.js来声明一个组件

Vue.component("xheader", {
    template: `
        <header :style="{border:'1px solid red'}">头部组件</header>
    `
})

构建异步加载方法

这个是异步创建script节点实现异步加载.js文件,从而实现异步加载xheader.js文件

// 实现异步加载js文件
function load(componentName, path) {
    return new Promise(function (resolve, reject) {
        var script = document.createElement('script');
        script.src = path;
        script.async = true;
        script.onload = function () {
            var component = Vue.component(componentName);
            if (component) {
                resolve(component);
            } else {
                reject();
            }
        };
        script.onerror = reject;
        document.body.appendChild(script);
    });
}

注册异步组件

new Vue({
    el: "#demo",
    template: `
        <div>
            <p>{{name}}</p>
            <xheader></xheader>
        </div>
    `,
    data: {
        name: "组件"
    },
    components: {
        xheader: function (resolve, reject) {
            // 这里可以用异步方法实现异步加载组件
            setTimeout(function () {
                load('xheader', 'xheader.js').then(resolve, reject);
            }, 3000)
        }
    }
})

参考文档

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions