Encounter problems, maintain a normal heart, the courage to face, always find a breakthrough.

preface

In this scenario, we have mixed text and images, and we have img tags and text in div. We send these to the server, and the server pushes the content to each user. What format of data does the server need? How do we render to the page when the client gets the data back from the server? Next, I will share my solution with you and show you the final result

Implementation approach

  • Listen for carriage return events
  • Gets all the children of the input box
  • Iterate over all child elements
  • Locate the IMG tag and text node
  • Gets the Alt id of the IMG tag, parsing the Alt id into a specific string
  • Call the interface to send the final parsed string
  • Gets the data returned by the interface and resolves custom identifiers
  • Gets the position of the custom identifier in the string, parsing it into an IMG tag
  • Render the parsed string

The implementation process

  • Listen for carriage return events
<div class="input-panel" ref="msgInputContainer"@keydown.enter.exact="sendMessage($event)" contenteditable="true" spellcheck="false"></div>
Copy the code
  • Implement the carriage return event function
sendMessage: function (event) {
        if (event.keyCode === 13) {
            // Prevents edit boxes from generating div events by default
            event.preventDefault();
            let msgText = "";
            // Get all the children of the input box
            let allNodes = event.target.childNodes;
            for(let item of allNodes){
                // Determine if the current element is an IMG element
                if(item.nodeName==="IMG"){
                    msgText += ` /${item.alt}/ `;
                }
                else{
                    // Get the value of the text node
                    if(item.nodeValue! = =null){ msgText += item.nodeValue; }}}console.log("Message capture succeeded :");
            console.info(msgText);
            // interface call to send messages to the server

                // 此处省略...

            //
            // Parse the data returned by the interface for rendering
            /** * Parses a particular string with regular expressions * finds where a particular string appears * traverses the JSON data in the configuration file, * determines whether the current keyword is in the configuration file * gets properties in the configuration file, generates an IMG tag ** / replaces a particular string with the generated IMG tag ** /
            let separateReg = /(\/[^/]+\/)/g;
            let finalMsgText = "";
            // Place the qualified strings in the array
            const resultArray = msgText.match(separateReg);
            if(resultArray! = =null) {for (let item of resultArray){
                    // Remove the/symbol from the string
                    item = item.replace(/\//g."");
                    for (let emojiItem of this.emojiList){
                        // Determine whether the captured string is the same as the string in the configuration file
                        if(emojiItem.info === item){
                            const imgSrc = require(`.. /assets/img/emoji/${emojiItem.hover}`);
                            const imgTag = `<img src="${imgSrc}" width="28" height="28" alt="${item}"> `;
                            // Replace the matching string with the IMG tag: global replace
                            msgText = msgText.replace(new RegExp(` /${item}/ `.'g'),imgTag);
                        }
                    }
                }
                finalMsgText = msgText;
            }else{
                finalMsgText = msgText;
            }
            console.log("Message parsing succeeded :");
            console.log(finalMsgText);
            const thisSenderMessageObj = {
                "msgText": finalMsgText,
                "msgId": Date.parse(new Date()),
                "avatarSrc": require(".. /assets/img/avatar.jpg")};// Render the page
            this.senderMessageList.push(thisSenderMessageObj);
            // Empty the input field
            event.target.innerHTML = ""; }},Copy the code

Record on pit

  • Remove the child elements of an editable div using removeChild(), innerHTML

    Get all of his child elements, traversal delete, but is unable to delete the return generated by the div, also do not know whether they write wrong, have found the error of friends, welcome comment area comments correction.

    let allNodes = event.target.childNodes;
     // Empty the input field
    for (let nodesItem of allNodes){
        event.target.removeChild(nodesItem);
    }
    
    // event.target.innerHTML = "";
    Copy the code

  • Incorrect regular expression

    When rendering the mixed content of parsed text and image, we need to convert/image description/to img tag, which seems to be ok but can’t be used after reading the regular expression document for a long time. Finally in the group for help, met a regular big guy, help me improve, finally realized my needs

    // My re
    let separateReg = /^\/.*\/$/g;
    // Help me improve the re
    let separateReg = /(\/[^/]+\/)/g;    
    Copy the code
  • Properly remove child elements from editable divs

    Generate div events by disabling carriage returns for editable divs, and then empty the contents of the input field

    event.preventDefault();
    event.target.innerHTML = "";
    Copy the code
  • Parse the string DOM properly

    V – use HTML

    <p v-html="item.msgText"/>
    Copy the code

Write in the last

  • If there are any errors in this article, please correct them in the comments section. If this article helped you, please like it and follow 😊
  • This article was first published in the Nuggets. If you need to reprint it, please leave a comment at 💌