首先实现一个vue组件模板
<template>
<div>{{title}}</div>
</template>
<script>
export default {
data () {
return {
title:'测试消息',
duration: 1500,
}
}
}
</script>
<style>
</style>
封装api
新建一个js文件.test.js
引入Vue和test.vue,并使用extend方法创建一个vue的子类HelloConstructor。
创建test方法,并export出去。实现这个方法,使他可以调用hello组件。
test方法的实现:
然后调用挂载函数$mount()方法获取vm,然后通过vm的$el属性获取DOM结构。
然后将获取的DOM结构挂载到body上。
import test from '../components/test.vue'
import Vue from 'vue'
let temp = Vue.extend(test)
const Msg = function (option) {
const newTemp = new temp({
data: option
})
let vm = newTemp.$mount();
console.log(vm,'vm')
let el = vm.$el;
console.log(el,'el')
document.body.appendChild(el)
setTimeout(() => {
document.body.removeChild(el)
newTemp.$destroy()
vm = null
},vm.duration)
}
export default Msg
使用
在别的js或者vue文件中,import引入test.js,就可以通过方法调用我们写的组件了
// js文件中或者vue文件的script标签中
import test from './hello.js';
test({
text: 'hello world'
});
还可以像下面这样将Hello方法挂载到Vue的prototype上:
import Vue from 'vue';
import test from './hello.js';
Vue.prototype.$msg= test;
vue组件中就可以this.$msg('hello world')这样使用。