A method and system for embedding Vue project code into react project
By dynamically creating iframes in React projects and embeding Vue project code, combined with cross-domain communication mechanism, the efficient code reuse problem of running Vue projects in React projects under the coexistence of multiple frameworks is solved, and efficient development and maintenance is achieved.
Patent Information
- Application Number
- CN202411838594.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-12-13
- Publication Date
- 2025-04-04
AI Technical Summary
In front-end projects where multiple frameworks coexist, it is difficult for existing technology to achieve efficient code reuse for Vue projects running in React projects, resulting in developers needing to manually adjust and optimize code, increasing workload and maintenance difficulty.
By dynamically creating iframe elements, embed Vue project code into React projects, and use cross-domain communication mechanism (window.postMessage) to realize two-way data transmission and event listening and processing between React projects and Vue components.
It realizes seamless integration of React projects and Vue components, reduces the cost of manual code synchronization, improves development efficiency and simplifies maintenance, and ensures data consistency and business logic continuity.
Smart Images

Figure CN119759444A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of component library processing, and in particular to code reuse between different front-end frameworks, especially for running a Vue project in a react project, and in particular to an embedding method and system for embedding a Vue project code into a react project. Background Art
[0002] In the development cycle of enterprise front-end projects, as the projects continue to iterate and evolve, the inconsistency of technology stacks has become a common problem. Especially when the project aims to adapt to the needs of future technology development, or to simplify later maintenance and follow the latest technology trends, multiple frameworks often coexist in the project. This phenomenon is specifically manifested in, for example, components with the same function need to be implemented in both the Vue component library and the React component library, or some template codes need to maintain multiple versions to adapt to different technology stack requirements.
[0003] Traditionally, a common solution to this problem of multiple frameworks coexisting is Figure 2 As shown in the figure, Vue code is converted to React code using online tools (such as Vue-to-React vue-convert-to-react) to repackage components. Compared with redeveloping from scratch, this method can save time to a certain extent. However, since these open source conversion tools are often based on technologies from a few years ago, they do not have enough support for newer APIs. For example, modern features such as React's hooks and functional components will generate outdated or deprecated API calls during the conversion process, such as $emit and props in Vue, which requires developers to perform a lot of manual adjustments and optimizations after the conversion.
[0004] Therefore, although this conversion tool simplifies the migration process from one framework to another to a certain extent, it has not actually significantly reduced the workload of developers, nor has it effectively improved development efficiency. Developers still need to invest a lot of time in adjusting and optimizing the code to ensure that the converted code complies with the best practices of modern front-end development and can fully utilize the features and advantages of the target framework. This shows that when facing front-end projects with multiple frameworks, it is necessary to explore more efficient and sustainable solutions to truly improve development efficiency and simplify project maintenance.
[0005] To this end, the present invention proposes an embedding method and system for embedding Vue project code into a React project. Summary of the invention
[0006] In view of this, the present invention hopes to provide an embedding method and system for embedding vue project code into react project, so as to solve or alleviate the technical problems existing in the prior art, that is, how to execute an embedding scheme to run vue project in react project without much cost to manually synchronize code, and at least provide a beneficial option for this; the technical solution of the present invention is implemented as follows:
[0007] First, a method to embed Vue project code into React project:
[0008] 1. Overview:
[0009] The present invention aims to achieve seamless integration and interaction between React projects and Vue components. By dynamically creating an iframe element and embedding it into a React component, the scheme provides a feasible solution for embedding Vue components in a React project. As an independent inline frame, iframe can load and run Vue components while maintaining isolation from the React project, avoiding the complexity and conflict caused by directly mixing the two technologies.
[0010] Through the cross-domain communication mechanism, the React project and the Vue component can achieve two-way data transmission and event monitoring and processing, thus achieving close collaboration between the two. This solution fully utilizes the respective advantages of React and Vue, allowing developers to flexibly introduce and utilize the functions of Vue components without sacrificing the existing project structure and code, further enriching the business scenarios and user experience of the React project.
[0011] (II) Technical solution:
[0012] To achieve the above technical objectives, given the React project code and externally input parameters and data, the present invention chooses to execute the following implementation method.
[0013] 2.1 Step S1, data input:
[0014] Read and load the React project, triggering the business scenario that needs to embed the Vue component. Receive external parameters and data through the state management of the React component.
[0015] 2.1.1 Step S100, read the React project code:
[0016] Read the source code files of the React project from the storage medium (such as a hard disk), execute the initialization script of the React project, set the basic configuration and environment of the project, and load the React framework and related dependent libraries.
[0017] 2.1.2 Step S101, triggering a business scenario:
[0018] According to user operations or external events, trigger the business scenarios that need to embed Vue components and the location and layout of embedded Vue components. Initialize the state management of React components, including Redux or Context. Then read the parameters and data passed in from the outside and store them in the state management, and then pass the parameters and data passed in from the outside as properties (props) to the React components that need to embed Vue components.
[0019] 2.1.3 Step S102, prepare to embed Vue components:
[0020] Prepare the source code and communication mechanism (such as iframe or Web Components) of the embedded Vue component according to business requirements and parameter data.
[0021] The React project has been initialized, and the business scenario that needs to embed Vue components has been triggered, and it is ready to receive and process the data and events of Vue components. The state management has stored the external parameters and data, which can be used for subsequent operations.
[0022] 2.2 Step S2, processing:
[0023] When the internal logic of the React component determines that the Vue component needs to be loaded, the iframe creation function is executed, the iframe element is dynamically created and its properties are set, and then the iframe element is inserted into the DOM structure of the React component; at the same time, the loading event of the iframe is listened to. When the iframe is loaded, the props of the React project are mounted on the window object of the iframe.
[0024] The input of this step includes:
[0025] (1) The result of the internal logic judgment of the React component (Vue component needs to be loaded);
[0026] (2) The URL of the Vue component;
[0027] (3) iframe attribute settings (including src, scrolling, width, height, border, and sandbox);
[0028] (4) React component props data;
[0029] The output after this step is completed includes:
[0030] (1) The iframe element has been created and set up and inserted into the DOM structure of the React component.
[0031] (2) The iframe's loading event has been monitored, and after loading is complete, the React component's props data is mounted on the iframe's window object.
[0032] The sub-steps of this step are as follows:
[0033] 2.2.1 Step S200, determine whether the Vue component needs to be loaded:
[0034] If necessary, execute the subsequent steps; otherwise, end the current process.
[0035] 2.2.2 Step S201, create an iframe function to execute:
[0036] Call the predefined function to create an iframe and start executing the iframe creation logic.
[0037] 2.2.3 Step S202, dynamically create an iframe element:
[0038] Use JavaScript's document.createElement method to dynamically create an iframe element. Store the created iframe element in a variable for subsequent operations.
[0039] 2.2.4 Step S203, set iframe attributes:
[0040] Set the properties of the iframe according to the input parameters, including src (URL pointing to the Vue component), scrolling, width, height, border, and sandbox;
[0041] Insert the iframe into the DOM structure of the React component: After determining the insertion position of the iframe in the React component, use JavaScript's DOM operation method to insert the iframe element into the specified DOM structure.
[0042] 2.2.5 Step S204, monitor the loading event of the iframe:
[0043] When the iframe is loaded, the callback function in the event listener is triggered.
[0044] 2.2.6 Step S205, mount the props of the React project to the window object of the iframe:
[0045] In the callback function after the iframe is loaded, get the window object of the iframe. Mount the props data of the React component to the window object of the iframe so that the Vue component can access this data.
[0046] 2.3 Step S3, data output:
[0047] Create a script element inside the iframe and inject the packaged Vue component code into the iframe's document to load the Vue component;
[0048] The Vue component is initialized and rendered, and the corresponding business logic is executed according to the props and data passed from the React project;
[0049] The Vue component communicates cross-domain with the React project, sends messages through window.postMessage, and listens and processes these messages in the React project through addEventListener.
[0050] The input of this step includes:
[0051] (1) The iframe element (created and inserted into the React component’s DOM structure)
[0052] (2) Packaged Vue component code;
[0053] (3) props and data passed from the React project;
[0054] The output after this step is completed includes:
[0055] (1) The Vue component is successfully loaded and rendered in the iframe.
[0056] (2) A cross-domain communication mechanism is established between the Vue component and the React project, which can send and receive messages to each other.
[0057] (3) The React project can listen to and process messages from the Vue component, and execute corresponding business logic or update status based on the message content.
[0058] The sub-steps of this step are as follows:
[0059] 2.3.1 Step S300, create a script element inside the iframe and inject the Vue component code:
[0060] Use JavaScript to create a new script element in the iframe's contentDocument. Store the script element in a variable for later manipulation.
[0061] Set the packaged Vue component code as text content to the textContent attribute of the script element. Add the script element to the head or body of the iframe's document to execute the code in it.
[0062] 2.3.2 Step S301, load Vue component:
[0063] When the script element is added to the iframe's document, the Vue component is initialized and starts the rendering process according to its internal logic.
[0064] 2.3.3 Step S302, Vue component initialization and rendering:
[0065] During the initialization process, the Vue component processes the props and data passed from the React project. Based on the props and data, the Vue component executes the corresponding business logic and updates its DOM structure to reflect the current state.
[0066] 2.3.4 Step S303, cross-domain communication and message sending:
[0067] In the Vue component, define the message content and format that needs to be sent to the React project. In the React project, listen to the message event from the iframe through addEventListener.
[0068] In the Vue component, use the window.postMessage method to send messages to the React project. The message content can include the state of the Vue component, user interaction results, or / and other business-related data.
[0069] 2.3.5 Step S304, monitor and process messages:
[0070] In the React project, after addEventListener listens to the message from the iframe, it triggers the callback function and updates the state of the React component according to the received message content.
[0071] 2.4 Step S4, Interaction Phase:
[0072] When a user interacts with a Vue component, an event is triggered or data is changed; the internal state of the Vue component is updated, and after the updated data or event is passed to the React project through cross-domain communication, its internal state is updated or the corresponding business logic is executed.
[0073] The input of this step includes:
[0074] (1) User interaction with Vue components (such as clicks, input, etc.);
[0075] (2) The internal state of the Vue component;
[0076] (3) Cross-domain communication mechanism (established);
[0077] The output after this step is completed includes:
[0078] (1) The internal state of the Vue component is updated and a cross-domain message is sent as needed.
[0079] (2) The React project has received and processed the message from the Vue component, updated the internal state or executed the corresponding business logic.
[0080] (3) The user interface has been updated based on the latest status and data.
[0081] The sub-steps of this step are as follows:
[0082] 2.4.1 Step S400, capturing user interaction behavior:
[0083] When the Vue component listens to user interaction (such as clicking a button or changing the content of an input box), the event processing function inside the Vue component is triggered. The event processing function updates the internal state of the Vue component based on the user interaction behavior, such as data modification, property change, or adjustment of the component's internal logic.
[0084] 2.4.2 Step S401, sending a cross-domain message:
[0085] The Vue component uses the window.postMessage method to send updated data or events as messages to the React project. The React project receives messages from the Vue component through the addEventListener listener added previously. The listener callback function is triggered and receives the message as a parameter.
[0086] 2.4.3 Step S402, processing cross-domain messages:
[0087] The React project parses and processes the received message in the callback function. Updates the internal state of the React component or executes the corresponding business logic according to the message content. If necessary, the React component re-renders the interface according to the updated internal state. The user interface reflects the latest state and data.
[0088] 2.5 Step S5, Unloading Phase:
[0089] When the Vue component is no longer needed, the internal logic of the React component executes the function of uninstalling the iframe; removes the iframe element from the DOM structure of the React component, and performs cleanup work (including removing event listeners and releasing resources).
[0090] The input of this step includes:
[0091] (1) The result of the internal logic judgment of the React component (Vue component is no longer required);
[0092] (2) The created iframe element and its related resources;
[0093] The output after this step is completed includes:
[0094] (1) The iframe element has been removed from the React component’s DOM structure.
[0095] (2) All iframe-related event listeners have been removed.
[0096] (3)The resources occupied by the iframe have been released.
[0097] The sub-steps of this step are as follows:
[0098] 2.5.1 Step S500, execute the function of uninstalling the iframe:
[0099] Call the predefined function to uninstall the iframe to execute the uninstall logic of the iframe. Use JavaScript's DOM operation method to find the position of the iframe element in the React component DOM structure. Remove the iframe element from its parent node to achieve uninstallation.
[0100] 2.5.2 Step S501, remove the event listener:
[0101] Traverse the iframe element and all event listeners added inside it. Use the removeEventListener method to remove these event listeners to ensure that there is no memory leak.
[0102] 2.5.3 Step S502, releasing resources:
[0103] Releases all resources used by the iframe element, including memory, timers, and network requests.
[0104] (III) Mechanism for solving technical problems:
[0105] 3.1 Isolation of iframe:
[0106] Iframe provides a relatively independent operating environment for the Vue project, allowing the Vue project to be loaded and run independently in the React project without making a lot of modifications to the React project itself. Due to the isolation of iframe, the DOM structure, style, and script between the Vue project and the React project are isolated, avoiding style conflicts, script errors, and other problems caused by direct mixing of the two.
[0107] React components use JavaScript to dynamically create iframe elements and set their properties (such as src, size, border, etc.) as needed. This makes the creation and use of iframes more flexible and can be dynamically adjusted according to business scenarios. The src attribute of the iframe points to the entry URL of the Vue project. When the iframe is inserted into the DOM, the browser automatically loads and runs the Vue project. In this way, the Vue project is loaded into the iframe as a separate page, and the React project exists as the host page.
[0108] 3.2 Cross-domain communication technology:
[0109] Since the Vue project and the React project are located in different sources (domain names, protocols or ports), cross-domain communication technology is needed to achieve data exchange between the two. The window.postMessage method allows secure communication between windows of different sources. In the React project, addEventListener is used to listen to the postMessage event from the Vue project; in the Vue project, window.postMessage can also be used to send messages to the React project. In this way, the two can achieve two-way data transmission and event monitoring and processing.
[0110] 3.3 Automation and reduction of manual synchronization costs:
[0111] Through the above technical mechanism, the React project can automatically integrate the Vue project without a lot of manual code synchronization work. This greatly reduces the integration cost and maintenance difficulty. Using cross-domain communication technology, the React project and the Vue project can share and update data in real time, ensuring data consistency and business logic continuity between the two.
[0112] On the second aspect, an embedding system that embeds Vue project code into React project:
[0113] The system includes a memory and a processor connected to the memory, wherein the memory stores program instructions and when the program instructions are executed by the processor, the processor is used to implement the embedding method as described above, wherein the processor is connected to:
[0114] (1) Cross-domain communication mechanism module for data exchange: Since React projects and Vue components (loaded through iframe) are usually located in different sources (domain names, protocols or ports), cross-domain communication technology is needed to achieve data exchange. The main sub-modules include:
[0115] (1.1) The window.postMessage submodule responsible for reading the API: reads the API introduced by HTML5, allowing secure communication between windows from different sources.
[0116] (1.2) The postMessage event submodule responsible for monitoring: In the React project, use addEventListener to monitor the postMessage event from the Vue component; in the Vue component, use window.postMessage to send messages to the React project. In this way, the two can achieve two-way data transmission.
[0117] (2) Data processing module used for React projects to send data to Vue components, and for Vue components to send data back to React projects:
[0118] When executing this solution, the flow of the data processing module is as follows:
[0119] P1. React project sends data to Vue component;
[0120] P2. The React component sends data to the Vue component in the iframe through the window.postMessage method;
[0121] P3. After receiving the data, the Vue component obtains the data by listening to the message event;
[0122] P4. Vue components send data back to React projects;
[0123] P5. After processing data or certain events, the Vue component also uses the window.postMessage method to send data back to the React project;
[0124] P6, React project listens to these messages through the previously set eventListener, and performs corresponding processing or updates the UI based on the received data.
[0125] Compared with the prior art, the present invention has the following beneficial effects:
[0126] 1. Flexibility and compatibility of technology stack: The technical solution of the present invention allows Vue components to be seamlessly embedded in React projects, making full use of the advantages of the two major front-end frameworks of React and Vue, and improving the flexibility of the technology stack. It solves the complexity and conflict problems caused by the direct mixed use of React and Vue, allowing developers to flexibly introduce and utilize the functions of Vue components without sacrificing the existing project structure and code.
[0127] 2. Development efficiency and cost savings: By dynamically creating iframes and cross-domain communication technology, the technical solution of the present invention realizes the integration between React projects and Vue components without a lot of manual code synchronization work, significantly reducing the integration cost and maintenance difficulty. Developers can quickly integrate existing Vue components or projects into React applications without rewriting or refactoring code, thereby improving development efficiency.
[0128] 3. User experience and business value: The technical solution of the present invention enables the React project to utilize the specific functions or interactions provided by the Vue component, enriching the business scenarios and user experience of the application. Through cross-domain communication, real-time data sharing and updating can be achieved between the React project and the Vue component, ensuring data consistency and business logic continuity between the two, and improving the overall performance and response speed of the application.
[0129] 4. Maintainability and scalability: The present invention uses the isolation of iframe to ensure the independence between the React project and the Vue component, so that the codes, styles and scripts between the two will not interfere with each other, reducing the difficulty of maintenance. Furthermore, the technical solution of the present invention has good scalability, and Vue components can be easily added or replaced without causing a significant impact on the React project. BRIEF DESCRIPTION OF THE DRAWINGS
[0130] In order to more clearly illustrate the embodiments of the present application or the technical solutions in the prior art, the drawings required for use in the embodiments or technical descriptions will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present application. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative work.
[0131] Figure 1 It is a schematic diagram of the method flow of the present invention;
[0132] Figure 2 This is a schematic diagram of how to use traditional online tools;
[0133] Figure 3 It is a schematic diagram of the system composition of the present invention. DETAILED DESCRIPTION
[0134] In order to make the above-mentioned purposes, features and advantages of the present invention more obvious and easy to understand, the specific implementation methods of the present invention are described in detail below in conjunction with the accompanying drawings. In the following description, many specific details are set forth to facilitate a full understanding of the present invention. However, the present invention can be implemented in many other ways different from those described herein, and those skilled in the art can make similar improvements without violating the connotation of the present invention. Therefore, the present invention is not limited to the specific embodiments disclosed below;
[0135] It should be noted that the various embodiments in this specification are described in a progressive manner, and each embodiment focuses on the differences from other embodiments, and the same or similar parts between the various embodiments can be referred to each other. For the device disclosed in the embodiment, since it corresponds to the method disclosed in the embodiment, the description is relatively simple, and the relevant parts can be referred to the method part description.
[0136] Glossary:
[0137] (1) React project: A front-end project developed using the React framework, containing multiple React components for building user interfaces and interaction logic.
[0138] (2) Business scenarios of Vue components: In a React project, Vue components need to be embedded to handle specific business logic or user interface parts. This is usually because Vue components provide certain specific functions or interactions that the React project needs to utilize.
[0139] (3) iframe function: A function in the React component that is used to dynamically create and manage iframe elements. This function is responsible for setting the properties of the iframe and inserting it into the DOM structure of the React component.
[0140] (4) iframe element: An inline frame element in HTML that is used to embed another HTML page in the current page. In this solution, iframe is used to load and display Vue components.
[0141] (5) Attributes (src, scrolling, width, height, border, sandbox): used to set the source URL of the iframe, whether to display the scroll bar, width, height, border style, and security policy (such as restricting script execution).
[0142] (6) DOM structure of React components: The DOM elements and their hierarchical structure generated after the React components are rendered. This structure defines the layout and style of the components on the page.
[0143] (7) iframe loading event: This event is triggered when the iframe element has finished loading its content. In this solution, it is used to pass the props and other data of the React project to the Vue component after the Vue component has finished loading.
[0144] (8) Document of iframe: The HTML document object inside the iframe, through which the content in the iframe is accessed and manipulated, such as the script injected into the Vue component.
[0145] (9) Props: A technique for passing data between React components. In this solution, Props is used to pass the data and state of the React component to the embedded Vue component.
[0146] (10) Cross-domain communication: Communication between pages of different origins (domain names, protocols or ports). In this solution, the React project and the embedded Vue component are located in different domains, so cross-domain communication technology is needed to exchange data.
[0147] (11) window.postMessage: A cross-domain communication technology that allows pages from different sources to send messages through a shared window object. In this solution, it is used to pass data between the React project and the embedded Vue component.
[0148] (12) addEventListener: A method in JavaScript that is used to add an event listener to a specified object. In this solution, it is used to listen to iframe loading events and cross-domain messages from Vue components.
[0149] Embodiment 1: Figure 1 As shown, this embodiment provides a method for embedding the Vue project code of an online car-hailing APP into a react project. It includes:
[0150] In this embodiment, regarding step S1: data input in the online car-hailing APP, when a user needs to book a car, the React project triggers the business scenario embedded in the Vue component. At this time, the React component receives the parameters and data such as the departure place and destination entered by the user through state management (such as Redux).
[0151] Specifically, step S1 includes:
[0152] (1) User input: Users enter the parameters required for booking, such as departure point and destination, in the online ride-hailing APP interface built with React.
[0153] (2) State management: React components use state management tools (such as Redux) to receive and manage user input data.
[0154] (3) Trigger condition: When the user triggers the reservation function (for example, clicking the reservation button), the React component detects this behavior and prepares to load the Vue component.
[0155] In this embodiment, regarding step S2: Processing: The React component determines that the Vue component needs to be loaded to display the vehicle type and optional services. Execute the create iframe function, dynamically create the iframe element, and set its properties (such as src pointing to the URL of the Vue component). Insert the iframe into the DOM structure of the React component, and listen to the loading event of the iframe. After loading is completed, the props of the React project (such as the departure and destination entered by the user) are mounted on the window object of the iframe.
[0156] Specifically, step S2 includes:
[0157] (1) Loading judgment: The React component determines through logical judgment that the Vue component needs to be loaded to display the vehicle type and optional services.
[0158] (2) Create an iframe: execute a function to dynamically create an iframe element and set its properties, such as the src attribute pointing to the URL of the Vue component.
[0159] (3) Insert into DOM: Insert the created iframe into the DOM structure of the React component to ensure that it is in the correct position on the page.
[0160] (4) Listen for loading: Add a listener for the loading event to the iframe so that subsequent operations can be performed after the Vue component is loaded.
[0161] (5) Mount props: When the iframe is loaded, the props of the React project (such as the departure and destination entered by the user) are mounted on the window object of the iframe so that the Vue component can access this data.
[0162] In this embodiment, regarding step S3: data is output inside the iframe, a script element is created and the packaged Vue component code is injected into the document of the iframe. The Vue component is initialized and rendered, and the corresponding business logic (such as displaying optional vehicle types and services) is executed according to the props (departure point, destination) passed from the React project. The Vue component communicates cross-domain with the React project, sends messages (such as the vehicle type and service selected by the user) through window.postMessage, and listens and processes these messages in the React project.
[0163] Specifically, step S3 includes:
[0164] (1) Inject Vue code: Create a script element inside the iframe and inject the packaged Vue component code into the document of the iframe.
[0165] (2) Vue component initialization: Vue component code is executed, and the component is initialized and rendered into the iframe.
[0166] (3) Execute business logic: The Vue component executes the corresponding business logic based on the props (departure point, destination) passed from the React project, such as displaying optional vehicle types and services.
[0167] (4) Cross-domain communication: Vue components communicate with React projects across domains. Vue components send messages (such as the vehicle type and service selected by the user) through the window.postMessage method, and the React project listens and processes these messages on the top-level window.
[0168] In this embodiment, regarding step S4: Interaction phase: the user interacts with the Vue component (such as selecting a vehicle type, adding a service), triggering an event or changing data. The internal state of the Vue component is updated, and the updated data (such as the vehicle and service selected by the user) is passed to the React project through cross-domain communication. The React project receives and processes messages from the Vue component, updates its internal state (such as reservation details), and re-renders the interface based on the latest state and data.
[0169] Specifically, step S4 includes:
[0170] (1) User interaction: Users interact in Vue components, such as selecting vehicle type, adding services, etc.
[0171] (2) Update status: The internal status of the Vue component is updated based on user interaction.
[0172] (3) Data transfer: The Vue component passes updated data (such as the vehicle and service selected by the user) to the React project through cross-domain communication.
[0173] (4) Processing messages: The React project receives and processes messages from the Vue component and updates its internal state (such as appointment details).
[0174] (5) Re-rendering: The React project re-renders the interface based on the latest status and data to show the user the latest appointment details.
[0175] In this embodiment, regarding step S5: uninstallation phase: when the user completes the appointment and closes the Vue component, the internal logic of the React component executes the function of uninstalling the iframe. The iframe element is removed from the DOM structure of the React component, and all event listeners related to the iframe are removed, and the resources occupied by the iframe (such as memory, timer) are released.
[0176] Specifically, step S5 includes:
[0177] (1) Trigger uninstallation: When the user completes the appointment and closes the Vue component, the internal logic of the React component executes the function of uninstalling the iframe.
[0178] (2) Remove iframe: Remove the iframe element from the DOM structure of the React component to ensure a clean page.
[0179] (3) Remove event listeners: Remove all event listeners related to the iframe to avoid memory leaks.
[0180] (4) Release resources: Release the resources occupied by the iframe, such as memory, timers, etc., to ensure that the performance of the application is not affected.
[0181] In this embodiment, the execution program (javascript) of creating an iframe environment and loading the Vue component is as follows:
[0182]
[0183]
[0184]
[0185] In this embodiment, the execution program (javascript) of the Vue component is downloaded and used in the React project as follows:
[0186]
[0187]
[0188] The principles in the above procedure include:
[0189] (1) Creation and loading of iframe: Create an iframe element and set its attributes and styles. Insert the iframe into the DOM and set its loading event. In the loading event, mount the props of the React project to the window object of the iframe and set the message processing for cross-domain communication.
[0190] (2) Loading and executing Vue components: In the loading event of the iframe, the Vue component code is injected into the document of the iframe through the loadJS function. The Vue component is initialized and rendered, and the corresponding business logic is executed according to the props passed from the React project.
[0191] (3) Cross-domain communication: Vue components communicate with React projects across domains. Vue components send messages through the window.postMessage method, and React projects listen to and process these messages on the top-level window. Use the vue-cli-service build --target lib command to package the Vue components into a library and publish it to npm.
[0192] (4) Dynamically load Vue components: In a React project, dynamically load the npm package of the Vue component through the import() function and pass it as a module to the iframe. This allows the Vue component to be used flexibly in a React project without directly embedding it into the React component tree.
[0193] Embodiment 2: Figure 2 As shown, based on the first embodiment, this embodiment further provides an embedding system for embedding the Vue project code into the React project:
[0194] The system includes a memory and a processor connected to the memory, wherein the memory stores program instructions and when the program instructions are executed by the processor, the processor is used to implement the embedding method as described above, wherein the processor is connected to:
[0195] (1) Cross-domain communication mechanism module for data exchange: Since React projects and Vue components (loaded through iframe) are usually located in different sources (domain names, protocols or ports), cross-domain communication technology is needed to achieve data exchange. The main sub-modules include:
[0196] (1.1) The window.postMessage submodule responsible for reading the API: reads the API introduced by HTML5, allowing secure communication between windows from different sources.
[0197] (1.2) The postMessage event submodule responsible for monitoring: In the React project, use addEventListener to monitor the postMessage event from the Vue component; in the Vue component, use window.postMessage to send messages to the React project. In this way, the two can achieve two-way data transmission.
[0198] (2) Data processing module used for React projects to send data to Vue components, and for Vue components to send data back to React projects:
[0199] When executing this solution, the flow of the data processing module is as follows:
[0200] P1. React project sends data to Vue component;
[0201] P2. The React component sends data to the Vue component in the iframe through the window.postMessage method;
[0202] P3. After receiving the data, the Vue component obtains the data by listening to the message event;
[0203] P4. Vue components send data back to React projects;
[0204] P5. After processing data or certain events, the Vue component also uses the window.postMessage method to send data back to the React project;
[0205] P6, React project listens to these messages through the previously set eventListener, and performs corresponding processing or updates the UI based on the received data.
[0206] All the above embodiments only express the implementation methods of the relevant practical applications of the present invention, and the descriptions thereof are relatively specific and detailed, but they cannot be understood as limiting the scope of the invention patent. It should be pointed out that, for ordinary technicians in this field, several variations and improvements can be made without departing from the concept of the present invention, which all belong to the protection scope of the present invention. Therefore, the protection scope of the patent of the present invention shall be based on the attached claims.
[0207] For those skilled in the art, it can be further appreciated that the units and algorithm steps of each example described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of the two. In order to clearly illustrate the interchangeability of hardware and software, the composition and steps of each example have been generally described in the above description according to function. Whether these functions are performed in hardware or software depends on the specific application and design constraints of the technical solution. Professional and technical personnel can use different methods to implement the described functions for each specific application, but such implementation should not be considered to be beyond the scope of the present invention.
[0208] At the same time, those skilled in the art can understand that all or part of the processes in all the above-mentioned embodiments can be completed by instructing the relevant hardware through a computer program, and the computer program can be stored in a non-volatile computer-readable storage medium. When the computer program is executed, it can include the processes of the embodiments of the above-mentioned methods. Among them, any reference to memory, storage, database or other media provided in this application and used in the embodiments may include non-volatile and / or volatile memory. Non-volatile memory may include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM) or flash memory. Volatile memory may include random access memory (RAM) or external cache memory. As an illustration and not limitation, RAM is available in many forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), double data rate SDRAM (SSRSDRAM), enhanced SDRAM (ESDRAM), synchronous link (Synchlink) DRAM (SLDRAM), memory bus (Rambus) direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM).
Claims
1. A method for embedding a Vue project code into a React project, comprising a given React project code and externally input parameters and data, characterized in that: Follow these steps: S1, reads and loads the React project, triggers the business scenario that needs to embed the Vue component; receives external parameters and data through the state management of the React component; S2, when the internal logic of the React component determines that the Vue component needs to be loaded, the iframe creation function is executed and the iframe element is dynamically created and its attributes are set, and then the iframe element is inserted into the DOM structure of the React component; S3, create a script element inside the iframe and inject the packaged Vue component code into the document of the iframe to load the Vue component; S4, when the user interacts with the Vue component, the internal state of the Vue component is updated and the updated data or events are passed to the React project through cross-domain communication; S5, executes the uninstallation logic of the iframe, uses the DOM operation method of JavaScript to find the position of the iframe element in the DOM structure of the React component and removes the iframe element from its parent node.
2. The embedding method according to claim 1, characterized in that: The implementation method of S1 includes: S100, reads the source code file of the React project, executes the initialization script of the React project, sets the basic configuration and environment of the project, and loads the React framework and dependent libraries; S101, initialize the state management of the React component, including Redux or Context; then read the external parameters and data, store them in the state management, and then pass the external parameters and data as attributes to the React component that needs to be embedded in the Vue component; S102, preparing source code and communication mechanism of embedded Vue components according to business requirements and parameter data.
3. The embedding method according to claim 1, characterized in that: The implementation method of S2 includes: S200, determine whether the Vue component needs to be loaded, if so, execute the subsequent steps; otherwise, end the current process; S201, create an iframe; S202, using the document.createElement method of JavaScript to dynamically create an iframe element; S203, setting the properties of the iframe according to the input parameters, including src, scrolling, width, height, border, and sandbox; S204, when the iframe is loaded, the callback function in the event listener is triggered; S205, in the callback function after the iframe is loaded, the window object of the iframe is obtained, and the props data of the React component is mounted on the window object of the iframe.
4. The embedding method according to claim 3, characterized in that: In the S3, after the insertion position of the iframe in the React component is determined, the iframe element is inserted into the specified DOM structure using the DOM operation method of JavaScript.
5. The embedding method according to claim 1, characterized in that: The implementation method of S3 includes: S300, using JavaScript to create a new script element in the contentDocument of the iframe; S301, when the script element is added to the document of the iframe, the Vue component is initialized and the rendering process begins; S302, during the initialization process, the Vue component passes props and data from the React project, and based on the props and data, the Vue component updates its DOM structure; S303, in the React project, listen to the message event from the iframe through addEventListener; S304, in the React project, after addEventListener listens to the message from the iframe, it triggers the callback function and updates the state of the React component according to the received message content.
6. The embedding method according to claim 5, characterized in that: In the S300, it also includes setting the packaged Vue component code as text content to the textContent attribute of the script element, and adding the script element to the head or body of the document of the iframe to execute the code therein.
7. The embedding method according to claim 1, characterized in that: The implementation method of S4 includes: S400, when the Vue component monitors the user interaction behavior, the internal state of the Vue component is updated according to the user interaction behavior; S401, the Vue component uses the window.postMessage method to send updated data or events as messages to the React project; S402, the React project parses and processes the received message in the callback function.
8. The embedding method according to claim 1, characterized in that: The implementation method of S5 includes: S500, using a JavaScript DOM operation method to find the position of the iframe element in the React component DOM structure, and remove the iframe element from its parent node to achieve uninstallation; S501, remove the event listener; S502, release all resources occupied by the iframe element, including memory, timer and network request.
9. An embedding system using the embedding method according to any one of claims 1 to 8, characterized in that: The system includes a memory and a processor connected to the memory, wherein the memory stores program instructions and when the program instructions are executed by the processor, the processor is used to implement the embedding method according to any one of claims 1 to 8, wherein the processor is connected to: A cross-domain communication mechanism module for realizing data exchange; A data processing module used for React projects to send data to Vue components, and for Vue components to send data back to React projects.
10. The embedded system according to claim 9, characterized in that: The processing flow of the data processing module includes: P1. React project sends data to Vue component; P2. The React component sends data to the Vue component in the iframe through the window.postMessage method; P3. After receiving the data, the Vue component obtains the data by listening to the message event; P4. Vue components send data back to React projects; P5. After processing data or certain events, the Vue component also uses the window.postMessage method to send data back to the React project; P6. The React project listens to messages and processes or updates the UI based on the received data.