使用defineComponent,继承组件挂载到dom节点上。

274 阅读1分钟

这里只是简单记录一下,因为我并没有实现,可能在之后我会重新补充修正这篇文章。

发生的场景是在地图中加载点击之后的弹窗,弹窗中是一个相对复杂的table,弹窗的结构使用字符串标签"<div>test</div>",使用ui组件库或请求会不方便。

地图页面

但是我并没有在defineComponent写修改组件中的值,因为写了之后组件会报错

const MyMapPopup = defineComponent({
  extends: MapPopup,//引入的组件文件
  setup:MapPopup.setup
})

const popupHTML = '<div id="popup"></div>'
xzGSPopup.setLngLat([e.lngLat.lng, e.lngLat.lat]).setHTML(popupHTML).addTo(sgMap.value)

nextTick(() => {
  createApp(MyMapPopup).mount('#popup')
})
MapPopup页面

特别奇怪的是el-tabs等element组件会失效,只能再次引入。

<template>
  <el-tabs type="card" @tab-click="handleTabClick">
    <el-tab-pane label="User" name="first">user</el-tab-pane>
  </el-tabs>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ElTabPane, ElTabs} from 'element-plus'

defineOptions({
  name: 'mapPopup'
})

</script>

<style lang="scss" scoped>

</style>

通过查gpt还有其他写法

import { defineComponent } from 'vue';
import BaseComponent from './BaseComponent.vue';

export default defineComponent({
  extends: BaseComponent,
  data() {
    return {
      // 修改继承的组件的值
      customValue: 'Custom Value',
    };
  },
});
//组件
<template>
  <div>
    <h1>{{ title }}</h1>
    <p>{{ description }}</p>
  </div>
</template>

<script>
export default {
  name: 'BaseComponent',
  data() {
    return {
      title: 'Base Title',
      description: 'Base Description',
    };
  },
};
</script>

现在还有一个
import { createApp } from 'vue';
import ExistingComponent from './ExistingComponent.vue';

// 创建一个应用
const app = createApp({});

// 创建一个包装组件,用于修改已有组件的值
const WrapperComponent = {
  mounted() {
    // 修改被挂载组件中的值
    this.$refs.existingComponent.someValue = 'Modified Value';
  },
  render() {
    return <ExistingComponent ref="existingComponent" />;
  },
};

// 将包装组件挂载到指定的 DOM 节点上
app.mount(WrapperComponent, '#app');