当前位置:首页 > VUE

简易实现vue

2026-01-11 21:36:13VUE

实现一个简易 Vue 框架

以下是一个简易 Vue 框架的核心实现思路,包含数据响应式、模板编译和依赖收集等功能。

数据响应式

通过 Object.definePropertyProxy 实现数据劫持,监听数据变化:

class Observer {
  constructor(data) {
    this.walk(data)
  }

  walk(data) {
    if (!data || typeof data !== 'object') return
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
    })
  }

  defineReactive(obj, key, val) {
    this.walk(val)
    const dep = new Dep()
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get() {
        Dep.target && dep.addSub(Dep.target)
        return val
      },
      set(newVal) {
        if (newVal === val) return
        val = newVal
        dep.notify()
      }
    })
  }
}

依赖收集

实现一个简单的发布-订阅模式来管理依赖:

class Dep {
  constructor() {
    this.subs = []
  }

  addSub(sub) {
    this.subs.push(sub)
  }

  notify() {
    this.subs.forEach(sub => sub.update())
  }
}

Dep.target = null

编译器

实现简单的模板编译功能:

class Compiler {
  constructor(el, vm) {
    this.$vm = vm
    this.$el = document.querySelector(el)
    if (this.$el) {
      this.compile(this.$el)
    }
  }

  compile(node) {
    const childNodes = node.childNodes
    Array.from(childNodes).forEach(child => {
      if (this.isElement(child)) {
        this.compileElement(child)
      } else if (this.isInterpolation(child)) {
        this.compileText(child)
      }
      if (child.childNodes && child.childNodes.length > 0) {
        this.compile(child)
      }
    })
  }

  isElement(node) {
    return node.nodeType === 1
  }

  isInterpolation(node) {
    return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
  }

  compileElement(node) {
    const attrs = node.attributes
    Array.from(attrs).forEach(attr => {
      const attrName = attr.name
      const exp = attr.value
      if (this.isDirective(attrName)) {
        const dir = attrName.substring(2)
        this[dir] && this[dir](node, exp)
      }
    })
  }

  isDirective(attr) {
    return attr.startsWith('v-')
  }

  compileText(node) {
    const exp = RegExp.$1.trim()
    this.update(node, exp, 'text')
  }

  text(node, exp) {
    this.update(node, exp, 'text')
  }

  update(node, exp, dir) {
    const fn = this[dir + 'Updater']
    fn && fn(node, this.$vm[exp])
    new Watcher(this.$vm, exp, value => {
      fn && fn(node, value)
    })
  }

  textUpdater(node, value) {
    node.textContent = value
  }
}

观察者

实现 Watcher 来连接视图和模型:

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm
    this.key = key
    this.cb = cb
    Dep.target = this
    this.oldValue = vm[key]
    Dep.target = null
  }

  update() {
    const newValue = this.vm[this.key]
    if (newValue !== this.oldValue) {
      this.cb(newValue)
      this.oldValue = newValue
    }
  }
}

Vue 主类

整合以上功能实现 Vue 类:

class Vue {
  constructor(options) {
    this.$options = options
    this.$data = options.data
    new Observer(this.$data)
    this.proxyData(this.$data)
    new Compiler(options.el, this)
  }

  proxyData(data) {
    Object.keys(data).forEach(key => {
      Object.defineProperty(this, key, {
        get() {
          return data[key]
        },
        set(newVal) {
          data[key] = newVal
        }
      })
    })
  }
}

使用示例

<div id="app">
  <p>{{ message }}</p>
  <button v-text="btnText"></button>
</div>

<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue',
      btnText: 'Click me'
    }
  })
</script>

这个简易实现包含了 Vue 的核心功能:数据响应式、依赖收集和模板编译。实际 Vue 框架还包含虚拟 DOM、组件系统等更多复杂功能,但以上代码展示了 Vue 响应式原理的基本实现方式。

简易实现vue

标签: 简易vue
分享给朋友:

相关文章

验证码实现vue

验证码实现vue

验证码实现(Vue) 使用组件库(如Element UI) Element UI提供了现成的验证码组件,可直接集成到Vue项目中。 安装Element UI: npm install elemen…

vue实现文档

vue实现文档

Vue 实现文档的方法 在 Vue 中实现文档功能可以通过多种方式,包括使用富文本编辑器、Markdown 解析或直接渲染 HTML。以下是几种常见的实现方法。 使用富文本编辑器 富文本编辑器如…

vue实现单词反转

vue实现单词反转

实现思路 在Vue中实现单词反转功能,可以通过多种方式完成。核心思路是利用JavaScript的字符串处理方法,将输入的单词或句子拆分为数组,反转数组后再拼接成字符串。 方法一:使用计算属性 通过计…

vue实现检测数组

vue实现检测数组

Vue 中检测数组变化的方法 Vue 的响应式系统无法直接检测到数组的某些变化,因为 JavaScript 的限制。以下是一些解决方案: 使用 Vue.set 或 this.$set Vue 提供…

vue实现裁剪头像

vue实现裁剪头像

Vue 实现头像裁剪功能 实现头像裁剪功能通常需要结合第三方库如 cropperjs 或 vue-cropper。以下是两种常见实现方式: 使用 vue-cropper 库 安装依赖: np…

vue怎么实现页面返回

vue怎么实现页面返回

Vue 实现页面返回的方法 在 Vue 中实现页面返回功能,可以通过以下几种方式完成,具体取决于项目使用的路由模式和技术栈。 使用 Vue Router 的编程式导航 通过 this.$route…