在了解了 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-JS 及 remote-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 所要求的.
来源: http://www.jianshu.com/p/576bbf8bd128