怎么使用create-api,入门版

265 阅读1分钟

create-api是黄轶老师写的,github地址
插件,是让某个组件以api的方式,能动态插入到body的下面,很像弹出层。
我个人目前觉得,弹出全局页面非常适合。

缺点

  • 弹出的组件数据并不会根据父组件的数据变动,但是使用store可以避免这个问题
  • 弹出的组件样式并不会完全scoped,所以当样式不对的时候,排除下这个问题
  • 弹出的组件记得最大的盒模型设置fixed,以及背景色,以此盖住原有页面

使用大概步骤

这边是使用的初级版。

1. 安装:

npm install vue-create-api

2. 写个普通的Hello组件:

<!-- Hello.vue -->
<template>
  <div class="box">
    {{ content }}
    <div @click="hidePage">取消</div>
    <slot name="other"></slot>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  name: 'hello',
  props: {
    content: {
      type: String,
      default: 'Hello'
    }
  },
  data(){
      return {

      }
  },
  methods: {
    hidePage(e) {
      this.$emit('hidePage', e)
    }
  }
}
</script>
<style scoped>
.box {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 2;
  /* 这里fixed布局全屏覆盖,之后设置背景色,这样就完全看不到下面图层的样式 */
  background-color: #69f;
}
</style>

3. 某页面用的时候

<!-- createApi.vue -->
<template>
  <div class="about">
    <h1>This is an about page</h1>
    <div @click="clickShowHello">点击显示hello</div>
  </div>
</template>

<script>
import Vue from "vue";
import Hello from "@/components/Hello.vue";
import CreateAPI from "vue-create-api";
Vue.use(CreateAPI);
// 这行就是创建 this.$createHello,常用的话直接在main那边创建,也可Hello.$create(config, renderFn);
Vue.createAPI(Hello, true);
export default {
  created() {
    // 这边因为create只创建一次实例,一旦移除需要将实例移除
    this.instanceHello = null;
  },

  methods: {
    clickShowHello() {
      // 先定义移除hello组件的方法,在点击取消的时候调用
      const removeHello = () => {
        this.instanceHello && this.instanceHello.remove();
      };
      // 这里就是使用,使用之后在body那边就插入了Hello组件,和#app同级
      this.instanceHello = this.$createHello(
        {
          //   Hello组件里的props在这里传递
          $props: {
            content: "I am from a vue component"
          },
          //   Hello组件里的向外派发的事件在这里
          $events: {
            hidePage: removeHello
          }
        },
        // Hello组件里的slot需要在这里,没有slot就不需要这个
        createElement => {
          return [
            createElement(
              "p",
              {
                slot: "other"
              },
              "other content"
            )
          ];
        }
      );
    }
  }
};
</script>

这里附上renderFn的写法