vue 封装 使用api 调用组件

本文介绍了一种在Vue中动态加载和显示组件的方法。通过封装API实现组件的按需加载,利用Vue的$mount方法获取组件实例并将其挂载到DOM上。文中还展示了如何在其他JS或Vue文件中调用该组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先实现一个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')这样使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值