Skip to content

any86/vue-create-root

Repository files navigation

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

🍭 不到1kb的小工具, 把vue组件变成this.$xxx命令, 支持插入组件到任意dom位置.

安装

npm i -S vue-create-root

cdn

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

快速开始

初始化后,组件内可以直接使用 this.$createRoot 渲染任意组件.

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

// xxx.vue
import UCom from '../UCom.vue';
{
    mounted(){
        // 默认组件被插入到<body>尾部
        this.$createRoot(UCom, {props: {value:'hello vue!'}});
        // 或者简写为:
        this.$createRoot(UCom, {value:'hello vue!'});
    }
}

自定义命令: this.$xxx

你可以定义任意命令类似饿了么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 要返回构造函数, 而不是直接生成组件?

🚀返回顶部