Hands-on practice, will be more profound understanding

In the introduction, after integrating Vue and some of its methods, we look at the second problem: rendering deep object properties, such as name.firstName

01. Compile functions

In the previous section, we compiled the following function:

    function compiler(template, data) {
      const childNodes = template.childNodes;
      for (const childNode of childNodes) {
        const type = childNode.nodeType;
        switch (type) {
          case 1: // Element node, recursive
            compiler(childNode, data);
            break;
          case 3: // Text node to check if mustache{{}}
            let txt = childNode.nodeValue;
            txt = txt.replace(regMustache, function (_, g) {
              // The 0th argument to this function is the matched one, for example {{name}}
              // The NTH argument is the contents of the NTH group, for example, name
              return data[g.trim()];
            })
            childNode.nodeValue = txt;
            break;
          default: break; }}}Copy the code

In line 14, the attribute value is obtained by the data[g.rim ()] method. Now, to get hierarchical attributes, you simply iterate through the path and get the attribute values in turn. So build a new function getValueByPath (data, path).

02, getValueByPath

@param {*} data object @param {string} path Path */
function getValueByPath(data, path) {
  const paths = path.split('. ');
  let res = data;
  for (const path of paths) {
    res = res[path];
  }
  return res;
}
Copy the code

03. Effect drawing

The HTML structure is as follows

  <header id="root">
    <p>{{name}}</p>
    <p>{{message}}</p>
    <p>{{name}} -- {{message}}</p>
    <p>{{deep.firstLevel.secondLevel}}</p>
  </header>
Copy the code

Render result:

The source code is available on Github

If you are interested, pay attention to my public number ~