Last time we converted the old Vue project from pure JS to js and TS. This time we are going to write react code in this vue project
I thought it would be a very troublesome thing, but I thought about it on my way home from work yesterday. Who knew when I was doing it today I went online and found a ready-made library
github.com/akxcv/vuera
Integrate the React Component with the Vue Component
Let’s test it out using the library example
// main.ts
import Vue from 'vue'
import { VuePlugin } from 'vuera'Vue.use(VuePlugin) /* ... * /Copy the code
// test.vue
<template>
<div>
<h1>Im a Vue component</h1>
<my-react-component :message="message" @reset="reset" />
</div>
</template>
<script>
import MyReactComponent from './MyReactComponent'
export default {
data () {
message: 'Hello from React! ',
},
methods: {
reset () {
this.message = ' '
}
},
components: { 'my-react-component': MyReactComponent },
}
</script>
Copy the code
// MyReactComponent.tsx
import React from 'react';
const App: React.FC = () => <div>my react component</div>;
export default App;
Copy the code
Json file will add this line to the compilerOptions {"compilerOptions": {
"jsx": "react"}},Copy the code
I tried it and found there was no problem
Vue – the router
The react Component cannot be added to the Component of the Router
The solution is to package a layer of Vue Component. Writing a common Wrapper method is the most convenient
//react-wrapper.js
import { ReactWrapper } from 'vuera';
export default function factoryReactWrapper(component) {
return {
components: { react: ReactWrapper },
render(createElement) {
return createElement('react', { props: { component }, }); }}; }Copy the code
// router.config.js
import factoryReactWrapper from './react-wrapper'
{
desc: 'test',
path: '/test',
component: factoryReactWrapper(MyReactComponent)
}
Copy the code
I tested it and it worked