39-mini-vue 实现解析 text 功能

实现解析 text 功能

  1. 测试
js 复制代码
describe("text", ()=>{
  it("simple text",()=>{
    const ast = baseParse("some text")
    expect(ast.children[0]).toStrictEqual({
      type: NodeTypes.TEXT,
      content: "some text"
    })
  })
})
  1. 思路:
    * 如果没有命中插值和元素的话,默认就走 Text 类型
    * 如果是 Text 类型,我们取出 content 值,然后推进 some text,也就是删除 some text
  2. 功能实现
js 复制代码
// compiler-core/parse.ts
function parseChildren(context) {
  const nodes: any[] = []
  let node: any
  const s = context.source
  if (s.startsWith('{{')) {
    node = parseInterpolation(context)
  } else if (s[0] === '<') {
    if (/[a-z]/i.test(context.source[1])) {
      node = parseElement(context)
    }
  }
  if (!node) { // ✅ text类型
    node = parseText(context)
  }
  nodes.push(node)
  return nodes
}
function parseText(context: any) { // ✅ 解析过程
  // 1. 获取 content
  const content = parseTextData(context, context.source.length)
  // 2. 推进
  advanceBy(context, content.length)
  return {
    type: NodeTypes.TEXT,
    content: "some text"
  }
}
// ✅ 函数抽离
function parseTextData(context:any, length: number) {
  return context.source.slice(0, length)
}

// src/ast.ts  
export const enum NodeTypes {
  INTERPOLATION,
  SIMPLE_EXPRESSION,
  ELEMENT,
  TEXT // ✅
}  
相关推荐
哆啦A梦15881 天前
Vue3魔法手册 作者 张天禹 016_vue3中一些特定用法介绍
前端·vue.js·typescript
henry1010101 天前
DeepSeek生成的网页小游戏 - 迷你高尔夫
前端·javascript·游戏·html
薛一半1 天前
React的组件
前端·javascript·react.js
广州华水科技1 天前
水库的单北斗GNSS变形监测系统是什么?主要有哪些应用?
前端
薛一半1 天前
React三大属性之props
前端·javascript·react.js
计算机毕设VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue连锁门店管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
用户5757303346241 天前
🔥 前端必考!AJAX 数据请求全解析,async true/false 区别一次搞懂
javascript
Wect1 天前
LeetCode 105. 从前序与中序遍历序列构造二叉树:题解与思路解析
前端·算法·typescript
麦麦大数据1 天前
F071_vue+flask基于YOLOv8的实时目标检测与追踪系统
vue.js·yolo·目标检测·flask·vue·视频检测
烤麻辣烫1 天前
正则表达式快速掌握
前端·javascript·学习·正则表达式·html