Simple function of simulating Vue replacement interpolation expression

Simple function of simulating Vue replacement interpolation expression

 HaoOuBa
2021-02-21 / 0 Comments / 256 Reading / Checking whether to include
reminder:
This article was last updated on February 21, 2021, and has not been updated for more than 1313 days. If the content or picture is invalid, please leave a message for feedback.
 <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div id="app"> {{ msg }}111{{ msg }} <div>{{msg}}</div> </div> <script> class Vue { constructor(options) { this.options = options /*Initialize compiling dom*/ this.compile() } compile() { let el = document.querySelector(this.options.el) if (! el) return console.warn('element not exist!') let childNodes = el.childNodes /*Recursive compilation node*/ childNodes.length && this.compileNodes(childNodes) } compileNodes(childNodes) { /*Loop Node*/ childNodes.forEach(node => { /*If it is a text node, replace the interpolation expression*/ if (node.nodeType === 3) { let reg = /\{\{\s*([^\{\{\}\}\s]+)\s*\}\}/g if (reg.test(node.textContent)) { /*$1 is the attribute value in the interpolation expression*/ let $1 = RegExp.$1 node.textContent = node.textContent.replace(reg, this.options.data[$1]) } } else { /*If it is not a text node, it will be recursive and has child nodes*/ node.childNodes.length && this.compileNodes(node.childNodes) } }) } } new Vue({ el: '#app', data: { Msg: 'Test data' } }) </script> </body> </html>
three

Comments (0)

cancel