封装一个可以通过api调用的组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yanzhi_2016/article/details/85614832

先实现一个vue组件

<!--hello.vue-->
<template>
  <div>{{text}}</div>
</template>
<script>
export default {
  name: 'hello',
  data () {
    return {
      text: ''
    }
  }
}
</script>

封装api

  1. 新建一个js文件。

  2. 引入Vue和hello.vue,并使用extend方法创建一个vue的子类HelloConstructor。

  3. 创建Hello方法,并export出去。实现这个方法,使他可以调用hello组件。

    Hello方法的实现:

    • 首先像实例化Vue一样实例化HelloConstructor。
    • 然后调用挂载函数$mount()方法获取vm,然后通过vm的$el属性获取DOM结构。
    • 然后将获取的DOM结构挂载到body上。
// hello.js
import Vue from 'vue';
import HelloTemplate from './hello.vue';

// 使用extend方法创建vue的子类
const HelloConstructor = Vue.extend(HelloTemplate);

// 使用这个方法调用hello组件
function Hello(options) {
  options = options || {};
  if (typeof options === 'string') {
    options = {
      text: options
    }
  }
  
  // 实例化子组件,然后获取到DOM结构并挂载到body上
  const helloInstence = new HelloConstructor({data: options});
  helloInstence.vm = helloInstence.$mount();
  document.body.appendChild(helloInstence.vm.$el);
}
export default Hello;

使用

在别的js或者vue文件中,import引入hello.js,就可以通过方法调用我们写的组件了。

// js文件中或者vue文件的script标签中
import Hello from './hello.js';

Hello('hello world');
// 或者
Hello({
  text: 'hello world'
});

还可以像下面这样将Hello方法挂载到Vue的prototype上:

import Vue from 'vue';
import Hello from './hello.js';
Vue.prototype.$hello = Hello;

vue组件中就可以this.$hello('hello world')这样使用。

以上是封装一个通过api调用组件的基本思路。业务需求需要另外在合适的地方实现。

需要注意一点:在合适的时候合适的地方调用组件的$destroy()方法销毁组件。

如果想通过Vue.use()方法使用组件,请看这篇博客

猜你喜欢

转载自blog.csdn.net/yanzhi_2016/article/details/85614832