项目:vue3 + vite4 + ant-design-vue4, 需要在此项目中使用已有的react组件,而不是重写;可以通过 veaury 工具实现;
- 安装 veaury(2.4.x版本),
@vitejs/plugin-react,@vitejs/plugin-vue和@vitejs/plugin-vue-jsx插件 - 配置 vite.config.js: veaury配置
// 可在vue项目中使用react|react项目中使用vue
import veauryVitePlugins from 'veaury/vite/index.js';
export default defineConfig({
plugins: [
// vue(), // 关闭vue插件
veauryVitePlugins({
// type设为vue时, 所有名为react_app目录中的文件的jsx将被react jsx编译,其他文件里的jsx将以vue jsx编译
type: 'vue'
})
]
})
- 安装
react,react-dom以及使用的 react 组件 - 在vue中使用react组件
<template>
<!-- 测试发现传递true值不能简写 -->
<VueComponent :foo="foo" :online="true">
<div>
children内容
</div>
</VueComponent>
</template>
<script setup>
import {applyReactInVue, applyPureReactInVue} from 'veaury';
import {ref} from 'vue';
const VueComponent = applyPureReactInVue(BasicReactComponent);
</script>
- 由于项目使用的react组件使用了
antd@4,样式会与ant-design-vue样式产生冲突,可通过修改 antd的prefixCls解决; less 配置需设置 javascriptEnabled: true
<script setup>
import { ConfigProvider } from 'antd';
import { applyPureReactInVue } from 'veaury';
const ReactConfigProvider = applyPureReactInVue(ConfigProvider);
</script>
<template>
<!-- 防止和ant-design-vue样式冲突 -->
<ReactConfigProvider prefixCls="antdr">
<slot></slot>
</ReactConfigProvider>
</template>
<style lang="less">
@import 'antd/dist/antd.less';
@ant-prefix: antdr;
@border-radius-base: 6px;
</style>
- 使用
ReactConfigProvider组件包裹,应用调整后的antd样式
<script setup>
import { applyReactInVue } from 'veaury';
import ReactConfigProvider from './ReactConfigProvider.vue';
// 这是一个React组件
const VueComponent = applyReactInVue(BasicReactComponent);
defineOptions({
name: 'VueComponent',
inheritAttrs: false
})
defineProps(['value']);
const emits = defineEmits(['update:value', 'change']);
const onChange = (value, ...args) => {
emits('update:value', value);
emits('change', value, ...args)
}
</script>
<template>
<ReactConfigProvider>
<VueComponent
v-bind="$attrs"
:value="value"
@change="onChange"
/>
</ReactConfigProvider>
</template>