Use React in Vue3 and Vue3 in React, And as perfect as possible
Last update: Jun 20, 2022
Veaury
Use React in Vue3 and Vue3 in React, And as perfect as possible!
What is Veaury?
Veaury (pronounced /ˈvjuːri/, inspired by 'beauty') is a tool library. It is built on the Vue and React framework. It's use cases include using both Vue and React in one app, migrating from React to Vue or from Vue to React, and using third-party Vue and React Components, such as antd, element-ui, vuetify.
The greatest feature
🌞
Support Vue3
🌈
Support Context - Share the context of all vue and react components.
💗
Support for using hooks across frameworks - You can use React's hooks in a Vue component, or you can use Vue's 'setup' function in a React component and use Vue's hooks in this function.
Legacy
The perfect tool library which can use React in Vue2 and Vue2 in React.
Do you want to preconfigure your project in advance?
In theory, you don't need to do additional configuration in a React project to support Vue, nor do you need to do additional configuration in a Vue project to support React.
If the React or Vue component you want to convert comes from a npm package, or has already been built, you can use applyReactInVue or applyVueInReact directly.
If you need to develop both Vue and React in a project, instead of just using an existing npm component, then you should do some configuration, usually configuring webpack.config.js and babel.config.js.
The directories dev-project-react and dev-project-vue3 in the project are the basic projects of the development environment of veaury, and they are also the two initial projects created by create-react-app and @vue/cli respectively.
Note: In the config/webpack.config.js of the React project and the vue.config.js of the Vue project, you can uncomment the veaury in alias to develop the source code of veaury
Setup: Run the command npm run setup:yarn or npm run setup:npm in the root directory of the main project to install the main project and two subprojects
Develop: Run the commands npm run dev:vue and npm run dev:react in the root directory of the main project for development
🏃
Migrating from React to Vue or from Vue to React
📲
Using third-party Vue and React Components, such as antd, element-ui, vuetify
Installation
# Install with yarn:
$ yarn add veaury
# or with npm:
$ npm i veaury -S
Usage
Vue in React - Basic usage
import{applyVueInReact}from'veaury'// This is a Vue componentimportBasicVueComponentfrom'./Basic.vue'import{useState}from'react'// Use HOC 'applyVueInReact'constBasic=applyVueInReact(BasicVueComponent)exportdefaultfunction(){const[foo]=useState('Hello!')return<Basicfoo={foo}><div>
the default slot
</div></Basic>}
React in Vue - Basic usage
the children
">
<template>
<Basic :foo="foo">
<div>
the children
div>
Basic>
template>
<script>import {applyReactInVue} from'veaury'// This is a React componentimportBasicReactComponentfrom'./react_app/Basic.jsx'import {ref} from'vue'exportdefault { components: {// Use HOC 'applyReactInVue' Basic:applyReactInVue(BasicReactComponent) },setup() {return { foo:ref('Hello!') } }}script>
Vue in React - Usage of events
import{applyVueInReact}from'veaury'importBasicVuefrom'./Basic.vue'import{useState}from'react'constBasic=applyVueInReact(BasicVue)exportdefaultfunction(){functiononClickForVue(){console.log('clicked!')}return<div>{/*Trigger with $emit('click') in Vue component*/}<BasiconClick={onClickForVue}/></div>}
React in Vue - Usage of events
">
<template>
<ReactButton @click="onClickForReact"/>
template>
<script>import {ref} from'vue'import {applyReactInVue} from'veaury'// This is a React ComponentimportReactButtonfrom"./react_app/Button.jsx"exportdefault { components: { ReactButton:applyReactInVue(ReactButton) },setup() {functiononClickForReact() {console.log('clicked!') }return { onClickForReact, } }}script>
Vue in React - Usage of slots
The usage of 'slots' is similar to the usage of 'v-slots' of Vue's jsx.
' in Vue Component
slot1:
this is slot1(namedSlot)
,
// Render with '' in Vue Component
slot2: ({value}) =>
this is slot2(scopedSlot), and receive value: {value}
,
// Render with '' in Vue Component
default:
this is children
}}/>
{/*another usage*/}
{{
slot1:
this is slot1(namedSlot)
,
slot2: ({value}) =>
this is slot2(scopedSlot), and receive value: {value}
,
default:
this is children
}}
}">
import{applyVueInReact}from'veaury'importBasicVuefrom'./Basic.vue'constBasic=applyVueInReact(BasicVue)exportdefaultfunction(){return<div>{/*just send children*/}<Basic>{/* Render with '' in Vue Component */}<div>this is children</div></Basic>{/*send v-slots*/}<Basicv-slots={{// Render with '' in Vue Componentslot1: <div>this is slot1(namedSlot)</div>,// Render with '' in Vue Componentslot2: ({value})=><div>this is slot2(scopedSlot), and receive value: {value}</div>,// Render with '' in Vue Componentdefault: <div>this is children</div>}}/>{/*another usage*/}<Basic>{{slot1: <div>this is slot1(namedSlot)</div>,slot2: ({value})=><div>this is slot2(scopedSlot), and receive value: {value}</div>,default: <div>this is children</div>}}</Basic></div>}
React in Vue - Usage of render props and React node
Named slots & scoped slots of Vue = React render props. Default slots $ children of Vue = React props.children. A named slot has a name prefixed with node: = React Node
this is slot2 (render props)
this content is passed from React: {{bar}}
this is slot3 (react node)
this is children (react node)
">
<template>
<Basic>
<templatev-slot:slot1>
<div>
this is slot1 (render props)
div>
template>
<templatev-slot:slot2="bar">
<div>
this is slot2 (render props)<br/>
this content is passed from React: {{bar}}
div>
template>
<templatev-slot:node:slot3>
<div>
this is slot3 (react node)
div>
template>
<div>
this is children (react node)
div>
Basic>
template>
<script>import {applyReactInVue} from'veaury'// This is a React ComponentimportReactBasicfrom"./react_app/Slots.jsx"exportdefault { components: { Basic:applyReactInVue(ReactBasic) }}script>
Context
Veaury will judge that if there is a wrapper layer of the same framework in the outer layer, Veaury will use React's Portal and Vue's Teleport instead of creating a new application instance every time.
It's a really awesome! Veaury can well pass the root node context to the child nodes, regardless of whether the node is wrapped or not.
This means that a Vue component used a React component, and then this React component used another Vue subcomponent. This Vue subcomponent can get the context of the outer Vue component.
Vue in React - Usage of Provider / useContext
bossName from Context: {bossName}
}
export default function () {
// Set context value
return
{/* This React component can get the context value from 'Provider' */}
}">
import{applyVueInReact}from'veaury'importBasicVuefrom'./Basic.vue'import{createContext,useContext}from'react'constBasic=applyVueInReact(BasicVue)// Create React context objectconstContext=createContext({})functionSubReactComponent(){// Get context valueconst{bossName}=useContext(Context)return<divclassName="slot">bossName from Context: {bossName}</div>}exportdefaultfunction(){// Set context valuereturn<Context.Providervalue={{bossName: 'God'}}><Basic>{/* This React component can get the context value from 'Provider' */}<SubReactComponent/></Basic></Context.Provider>}
React in Vue - Usage of Provide / Inject
bossName)
}
}
export default {
components: {
Basic: applyReactInVue(ReactBasic),
SubVueComponent
},
setup() {
// Use 'provide' to set the value of bossName
provide('bossName', 'God')
}
}
">
<template>
<Basic>
<SubVueComponent/>
Basic>
template>
<script>import {provide, inject, h} from'vue'import {applyReactInVue} from'veaury'// This is a React componentimportReactBasicfrom"./react_app/Basic"// This is a Vue componentconstSubVueComponent= {setup() {// get bossName from injectionconstbossName=inject('bossName')returnh('div', () => bossName) }}exportdefault { components: { Basic:applyReactInVue(ReactBasic), SubVueComponent },setup() {// Use 'provide' to set the value of bossNameprovide('bossName', 'God') }}script>
Usage of VueContainer in React Component
You can use the VueContainer component in a React component to display Vue components directly.
When React components in Vue components, VueContainer can display global Vue components registered in the upper-level Vue app.
' if 'vue-router' exists, You can use ''
return
}">
import{VueContainer}from"veaury"importBasicVuefrom'./Basic.vue'exportdefaultfunction(){constpassedProps={name: 'Mike'}// Render '' if 'vue-router' exists, You can use ''return<VueContainercomponent={BasicVue}{...passedProps}/>}
Vue in React, Usage of v-model / v-models
The usage of 'v-model' is similar to the usage of 'v-model' of Vue's jsx. The value type of the v-model property should be [ modelValue, modelSetter, argumentKey, argumentModifiers ] [ modelValue, modelSetter, argumentModifiers ] [ modelValue, modelSetter ] Additional 'argumentKey' attached property, such as v-model-god={[godValue, setGodValue]} = v-model={[godValue, setGodValue, 'god']}
import{applyVueInReact}from'veaury'importBasicVuefrom'./Basic.vue'importBasic1Vuefrom'./Basic1.vue'import{useState}from'react'constBasic=applyVueInReact(BasicVue)constBasic1=applyVueInReact(Basic1Vue)exportdefaultfunction(){const[foo,setFoo]=useState(Math.random())const[bar,setBar]=useState(Math.random())const[zoo,setZoo]=useState(Math.random())return<div><Basicv-model={[foo,setFoo]}v-model-bar={[bar,setBar]}/>{/**/}{/**/}{/**/}<Basic1v-models={{// The key value of 'modelValue' is equivalent to 'v-model'modelValue: [zoo,setZoo],//...otherModels}}/></div>}
HOC injectPropsFromWrapper
injectPropsFromWrapper is a higher order component.
When developing Vue and React applications at the same time, sometimes it is necessary to obtain the context of the React app inside the Vue component, and vice versa.
For example, to get information from react-router in Vue components, or to get state from vuex in React components.
This HOC can be used for both Vue and React components.
interfacepropsFromWrapper{[propName: string]: any;}typecomponent=object|FunctiontypecomputedModeReturn=()=>propsFromWrappertypedefaultModeReturn=propsFromWrapper|FunctiontypeallModeReturn=defaultModeReturn|computedModeReturntypeinjectionFunction<T=allModeReturn>=(props?: propsFromWrapper)=>T// types of injectPropsFromWrapperinterfaceinjectPropsFromWrapper<TextendsallModeReturn=allModeReturn>{(injectionFunction: injectionFunction<T>,component:component): component}
Usage of injecting React hooks in Vue component
React application uses Vue component, example to get react-router inside Vue component.
This is the Vue Component.
the path info from 'react-router': {{pathname + search}}
">
<template>
<divclass="vue-component">
<h3>This is the Vue Component.h3>
the path info from 'react-router': <spanstyle="font-weight: bold">{{pathname + search}}span><br/><br/>
<button @click="changeQuery">change querybutton>
div>
template>
<script>// This Vue component will be used in the React app and needs to use the react-router hooksimport { injectPropsFromWrapper } from'veaury'import { useLocation, useNavigate } from'react-router-dom'importReactfrom'react'functionReactInjectionHook (reactProps) {// React hooks can be used in this function// Use the hooks of react-router-domconstreactRouterLocation=useLocation()constnavigate=useNavigate()functionchangeQuery() {navigate(`?a=${Math.random()}`, {replace:true}) }// The returned object will be passed to the Vue component as propsreturn { pathname:reactRouterLocation.pathname, search:reactRouterLocation.search, changeQuery }}// 'injectPropsFromWrapper' returns the original Vue component and will register injectionHook.// When the Vue component is applied to the React app by 'applyVueInReact',// InjectionHook will be executed first, otherwise InjectionHook will not be executedexportdefaultinjectPropsFromWrapper(ReactInjectionHook, { props: { pathname:String, search:String, changeQuery:Function }})script>
Usage of injecting Vue hooks in React component
Vue application uses React component, example to get vue-router and vuex inside React component. There are two modes for injecting functions, 'setup' and 'computed' modes.
import{toRef}from'vue'import{useStore}from'vuex'import{useRoute,useRouter}from'vue-router'import{injectPropsFromWrapper}from'veaury'// This React component will be used in the Vue app and needs to use the vue-router and vuex hooks// setup modefunctionVueInjectionHookInSetupMode(vueProps){// Vue hooks can be used in this function// This function will be called in the 'setup' hook of the Vue wrapper componentconststore=useStore()constroute=useRoute()constrouter=useRouter()// The returned object will be passed to the React component as propsreturn{// you need to manually convert to proxy with 'setup' mode// otherwise it will not be responsivefullPath: toRef(route,'fullPath'),count: toRef(store.state,'count'),changeQuery: ()=>router.replace({query: {a: Math.random()}}),incrementCount: ()=>store.dispatch('increment')}}// computed modefunctionVueInjectionHookInComputedMode(vueProps){// The context of the function is binding with the proxy from the 'getCurrentInstance' hook// Returning a function represents the computed of the options api// All logic code should be written in this computed function.// The lifecycle cannot be used in this function. If you want to use the lifecycle, you can only use the 'setup' modereturnfunctioncomputedFunction(){return{fullPath: this.$route.fullPath,count: this.$store.state.count,changeQuery: ()=>this.$router.replace({query: {a: Math.random()}}),incrementCount: ()=>this.$store.dispatch('increment')}}}// The first parameter is the injection function.// Vue's injection function has two modes: 'setup' and 'computed'.// Refer to the case of the above two injection function types.// Also try replacing the first parameter with 'VueInjectionHookInComputedMode'exportdefaultinjectPropsFromWrapper(VueInjectionHookInSetupMode,function(props){return(<div>
This is the React Component
<span>
the path info from 'vue-router': <spanstyle={{fontWeight: 'bold'}}>{props.fullPath}</span><br/>
the count from 'vuex': <spanstyle={{fontWeight: 'bold'}}>{props.count}</span></span><br/><buttononClick={props.changeQuery}>change query</button><buttononClick={props.incrementCount}>increment count</button></div>)})
Note: If you use injection function to wrap the same component multiple times, the previous injection function will be overwritten.
Injection functions in 'computed' mode only support synchronous code
It should be ensured that the logic inside the injection function is a pure function, and business logic should not be added to the injection function. It is not recommended to use lifecycle or asynchronous calls in the injection function.
Usage of lazyReactInVue
<template>
<Basic/>
template>
<script>import { lazyReactInVue } from'veaury'exportdefault { components: {// import an async React component// It is also possible to use the full parameter of the Vue3 API 'defineAsyncComponent'// for example: lazyReactInVue({ loader: () => import('./react_app/Basic'), timeout: 3000 }) Basic:lazyReactInVue(() =>import('./react_app/Basic')) },}script>
1. Svg icons won't show in grafana/ui library react components
Hello there
I use vue 3, vite, grafana/ui, veaury
first of thank you very much for this library it surely helps a lot.
I try to use it with grafana/ui which is made up of react components internally. When I try to use a Button for example and pass an icon string prop it internally processes the svg with react-inline-svg and then uses a dom parser to get the node of the parsed svg text. For some reason it doesn't work for me. I do get the following error:
Which is located here:
And used first here:
Inside grafana_ui.js
One of the components in question:
The processed svg is correct:
data:image/svg+xml,%3csvg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3e%3cpath d='M12%2c6a.99974.99974%2c0%2c0%2c0-1%2c1v4H9a1%2c1%2c0%2c0%2c0%2c0%2c2h3a.99974.99974%2c0%2c0%2c0%2c1-1V7A.99974.99974%2c0%2c0%2c0%2c12%2c6Zm0-4A10%2c10%2c0%2c1%2c0%2c22%2c12%2c10.01146%2c10.01146%2c0%2c0%2c0%2c12%2c2Zm0%2c18a8%2c8%2c0%2c1%2c1%2c8-8A8.00917%2c8.00917%2c0%2c0%2c1%2c12%2c20Z'/%3e%3c/svg%3e
So this is the follow of the #5 issue, the CSS cant align correctly, i've try modifying the CSS file "@elastic/eui/dist/eui_theme_light.css"
but it does'nt seems to work
Here is what I have
And the same component in React
Reviewed by AimSteyz at 2022-05-05 12:08
4. file not found
Hi I am using it in stack bliz(right now I cant install vue in local machine, so I used js framework online compiler), I am using react in vue. and installed the following npm package already;
react,
react-dom
veaury
vue
However, it just shows the error ,
when I tried to import react component.
it just shows cant find the import file.
link:
Could you mind have a quick look? Appreciate that.
Reviewed by xudawww at 2022-03-16 15:37
5. Elastic UI ‘Failed to fetch dynamically imported module’
Hi,
when we try to display an icon of EuiIcon using veaury, we got this error
GET http://localhost:3000/node_modules/.vite/deps/assets/heart?import net::ERR_ABORTED 504 (Gateway Timeout) Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:3000/node_modules/.vite/deps/assets/heart?import
Step to reproduce the error:
Install Eui yarn add @elastic/eui @elastic/datemath @emotion/react moment prop-types
Import an EuiIcon and use the component
import React from 'react';import { EuiIcon } from '@elastic/eui';export default () => {return(<EuiIcon type="heart" />);}
Reviewed by AimSteyz at 2022-05-03 15:12
6. Work Perfectly but what about HMR?
Hey, good job!
Just wanted to know how I can get HMR working on react components?
I have Vue3 + Vite + Veaury and a component folder with a react project inside. When I modify the react files, I cannot see the UI updated in real time, I need to refresh the browser. How to get this work?
This is a framework which extends create-react-app to enables you to quickly build data-driven sites. This code is generated from the Datapod-for-React Core application.
?? DataFormsJS ?? A minimal JavaScript Framework, standalone React and Web Components, and JSX Compiler for rapid development of high quality websites and single page applications.