Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue异步组件 #19

Open
Wscats opened this issue Jan 11, 2018 · 0 comments
Open

vue异步组件 #19

Wscats opened this issue Jan 11, 2018 · 0 comments

Comments

@Wscats
Copy link
Owner

Wscats commented Jan 11, 2018

构建异步组件

先定义一个外部的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)
        }
    }
})

参考文档

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant