vue-create-root
TypeScript icon, indicating that this package has built-in type declarations

0.0.8 • Public • Published

vue-create-root NPM Version NPM Downloads npm bundle size (minified + gzip) codecov CircleCI

🍭 不到1kb的小工具, 把任意vue组件插入到任意dom位置, 默认<body>尾部.

实际意义

把一些"大尺寸的组件"放到<body>尾部, 防止父元素使用overflow:hidden而导致组件显示不全.

安装

npm i -S vue-create-root

cdn

https://unpkg.com/vue-create-root/dist/vue-create-root.umd.js

快速开始

下面把Test组件插入到<body>尾部.

main.js

import createRoot from 'vue-create-root';
Vue.use(createRoot);

Test.vue

export default{
    props:['value'],
    template: `<h1>{{value}}</h1>`
}

App.vue

import Test from '../Test.vue';
export default{
    mounted(){
        // 默认组件会被插入到<body>尾部
        this.$createRoot(Test, {value:'hello vue!'});
    }
}

API

$createRoot(tag, data, child, options)

第3,4个参数选填, options的默认值为:{ target = 'body', insertPosition = 'append' }

$createRoot的核心代码依赖于Vue.prototype.$createElement, 所以tag, data, child参数就是$createElement的参数, 具体使用方法可以参考Vue文档

target是目标元素的选择器, insertPosition有4个值, append代表插入到元素(<body>)尾部, 其他参数:

  • beforebegin: 在该元素本身的前面.
  • afterbegin:只在该元素当中, 在该元素第一个子孩子前面.
  • beforeend:只在该元素当中, 在该元素最后一个子孩子后面.
  • afterend: 在该元素本身的后面.

简写

如果$createRoot的第2个参数只传入props属性, 那么可以简写:

this.$createRoot(Test, {value:'hello vue!'});
// 完整写法
this.$createRoot(Test, {props:{value:'hello vue!'}});

返回值

$createRoot(Test)返回一个vue根实例(非Test实例), VueCreateRoot在根实例上定义了2个方法:$update$destroy.

$update(data,child)

$update用来更新Test组件(传入的组件), data,child$createRootdata,child.

const i = this.$createRoot(Test);
i.$update({value:'我变了!'});

$destroy

$destroy用来销毁$createRoot创建的根实例, 如:

const i = this.$createRoot(Test);
 
i.$destroy({value:'我变了!'});

进阶使用

自定义this.$alert

你可以定义任意命令类似饿了么UI, 比如this.$alert / this.$Message.success

// main.js
// 初始化插件, 把createRootClass方法挂到Vue上
Vue.use(createRoot);
 
// 包装组件
const C = Vue.createRootClass(UCom);
 
// 定义this.$alert命令
// props对应组件的props属性
Vue.prototype.$alert = (props) => new C(props);
// xxx.vue
this.$alert({isShow:true, content: "你好vue !"});

注意: 这里设计Vue.createRootClass(UCom)的意图是为了实现单/多例2种API, 比如上面的C的多例用法就是new C(), 而单例就是C.init().

更多

API

更多示例

为什么 Vue.createRootClass 要返回构造函数, 而不是直接生成组件?

🚀返回顶部

Readme

Keywords

none

Package Sidebar

Install

npm i vue-create-root

Weekly Downloads

1

Version

0.0.8

License

ISC

Unpacked Size

95.9 kB

Total Files

22

Last publish

Collaborators

  • russell-ne