美文网首页让前端飞Web前端之路
Vue单个页面引入CDN链接

Vue单个页面引入CDN链接

作者: 竿牍 | 来源:发表于2020-04-02 11:48 被阅读0次

在了解了render函数与createElement函数的基础上,想要实现Vue单个页面引入CDN链接就简单很多了。

  • 首先采用createElement创建不同资源类型(以js、css为例)的VNode
// js CDN
createElement('script', {
    attrs: {
        type: 'text/javascript',
        src: this.cdn
    }
})
// css CDN
createElement('link', {
    attrs: {
        rel: 'stylesheet',
        type: 'text/css',
        href: this.cdn
    }
})
  • 然后基于上述VNode,采用render创建函数式组件remote-jsremote-css
components: {
    'remote-js': {
        render(createElement) {
            return createElement('script', {
                attrs: {
                    type: 'text/javascript',
                    src: this.cdn
                }
            })
        },
        props: {
            cdn:  {
                type: String,
                required: true
            }
        }
    },
    'remote-css': {
        render(createElement) {
            return createElement('link', {
                attrs: {
                    rel: 'stylesheet',
                    type: 'text/css',
                    href: this.cdn
                }
            })
        },
        props: {
            cdn:  {
                type: String,
                required: true
            }
        }
    }
}
  • Vue单页面引入
<template>
    <div class="my-page">
        <remote-js cdn="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></remote-js>
        <remote-css cdn="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css"></remote-css>
    </div>
</template>
  • 彩蛋(=。=)
    如果你觉得render函数写起来很费劲的话,就可以利用Bable插件,在Vue 中使用 JSX ,让我们可以无限接近于模板语法。上述代码就变成下面这样了,好像是顺眼了一丢丢吧:
components: {
    'remote-js': {
        render(h) {
            return (
                <script type= 'text/javascript' src={this.cdn}></script>
            )
        },
        props: {
            cdn:  {
                type: String,
                required: true
            }
        }
    },
    'remote-css': {
        render(h) {
            return (
                <link rel='stylesheet' type='text/css' href={this.cdn} />
            )
        },
        props: {
            cdn:  {
                type: String,
                required: true
            }
        }
    }
}

PS:将 h 作为 createElement 的别名是 Vue 生态系统中的一个通用惯例,实际上也是 JSX 所要求的。

相关文章

网友评论

    本文标题:Vue单个页面引入CDN链接

    本文链接:https://www.haomeiwen.com/subject/trtxphtx.html