想在react项目中使用vue组件吗?

3,784 阅读1分钟

avatar.jpeg

起因

由于甲方爸爸最近的一些迷惑要求,小伙伴们正处在要么用vue重写整个项目(可是都不太会vue啊),要么在react组件中引用vue组件的境地。刚好我这段时间的任务不是很繁重,于是便开始调研解决方案。

u=283629586,4021767721&fm=253&fmt=auto&app=138&f=JPEG.webp

在网上查阅资料后找到了这个库,vuereact-combined,不得不说前人真是太牛了,这种场景都考虑到了吗。 这个库是基于vue2的,vue3的话可以看一下这个veaury,这2个库都支持vue和react互相引用。

实现

首先需要在项目引入 vue vue-loader vuereact-combined,这3个包就可以在react项目里使用vue组件了。 然后是在webpack配置里配置相应的loader和plugin。

 const VueLoaderPlugin = require('vue-loader/lib/plugin');
 rules: [
    {
      test: /\.vue$/,
      use: 'vue-loader'
    }
  ],
  plugins: [new VueLoaderPlugin()],

接下来我们写一个vue组件来测试一下

<template>
<div>
  <el-card >
    <div slot="header">
      <span>卡片名称</span>
      <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
    </div>
    <div v-for="o in list" :key="o">
      {{'列表内容 ' + o}}
    </div>
  </el-card>
</div>
</template>

<script>
import Vue from 'vue';
import { Card, Button } from 'element-ui';
Vue.use(Card);
Vue.use(Button);
export default {
  props: ['list'],
}
</script>

<style scoped>
</style>

在react组件中进行引入

import React, { useState } from 'react';
import { applyVueInReact } from 'vuereact-combined';
import { Button } from 'antd';
import Card from '@vue/card.vue';
const VueCard = applyVueInReact(Card);

const Test = () => {
  const [list, setList] = useState([]);
  const handleClick = () => {
    setList([...list, list.length + 1]);
  };
  return (
    <div style={{ margin: '0 100px' }}>
      <Button onClick={handleClick}>Add</Button>
      <VueCard list={list} />
    </div>
  );
};

export default Test;

效果如下

iShot_2023-02-10_15.19.29.gif 看起来还不错,再试一下事件绑定

react:
const Test = () => {
  const [list, setList] = useState<number[]>([]);
  const handleClick = () => {
    setList([...list, list.length + 1]);
  };
  const handleDel = (index: number) => {
    list.splice(index, 1);
    setList([...list]);
  };
  return (
    <div style={{ margin: '0 100px' }}>
      <Button onClick={handleClick}>Add</Button>
      <VueCard list={list} onDel={handleDel} />
    </div>
  );
};

vue: 
<div>
  <el-card >
    <div slot="header">
      <span>卡片名称</span>
    </div>
    <div v-for="(item, index) in list" :key="item">
      {{'列表内容 ' + index }}
      <el-button @click="onDel(index)">删除</el-button>
    </div>
  </el-card>
</div>
</template>
<script>
import Vue from 'vue';
import { Card, Button } from 'element-ui';
Vue.use(Card);
Vue.use(Button);
export default {
  props: ['list', 'onDel'],
}
</script>

效果如下:

iShot_2023-02-10_15.28.35.gif

nice啊,可以满足基本使用了,其他的骚操作就留给你们自己研究文档了,我得去搬砖了。

参考资料

zhuanlan.zhihu.com/p/514672320

github.com/devilwjp/vu…

github.com/devilwjp/ve…