当前位置:首页 > VUE

简单实现vue

2026-01-12 18:40:14VUE

实现一个简易 Vue 框架

以下是一个基于 JavaScript 的简易 Vue 实现,核心功能包括数据响应式、模板编译和依赖收集。

数据响应式

通过 Object.defineProperty 实现数据劫持:

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) {
    const dep = new Dep()
    this.walk(val)
    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()
      }
    })
  }
}

依赖收集系统

实现简单的发布-订阅模式:

简单实现vue

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(el) {
    const childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isElement(node)) {
        this.compileElement(node)
      } else if (this.isInterpolation(node)) {
        this.compileText(node)
      }
      if (node.childNodes && node.childNodes.length > 0) {
        this.compile(node)
      }
    })
  }

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

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

  compileText(node) {
    this.update(node, this.$vm, RegExp.$1, 'text')
  }

  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, this.$vm, exp)
      }
    })
  }

  isDirective(attr) {
    return attr.indexOf('v-') === 0
  }

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

  update(node, vm, exp, dir) {
    const updaterFn = updater[dir + 'Updater']
    updaterFn && updaterFn(node, vm[exp])
    new Watcher(vm, exp, function(value) {
      updaterFn && updaterFn(node, value)
    })
  }
}

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

观察者

实现 Watcher 类来连接响应式数据和视图:

简单实现vue

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) return
    this.cb(newValue)
  }
}

主类

整合所有功能的 Vue 类:

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

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

使用示例

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

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

这个实现包含了 Vue 的核心功能:

  • 数据响应式
  • 模板编译
  • 指令解析
  • 依赖收集和更新

可以根据需要进一步扩展功能,如添加计算属性、事件处理等。

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

相关文章

简易实现vue

简易实现vue

简易 Vue 实现思路 核心是数据劫持结合发布-订阅模式,通过 Object.defineProperty 或 Proxy 监听数据变化,触发视图更新。 数据劫持实现 class Observer…

vue卖座网实现

vue卖座网实现

Vue 卖座网实现 项目结构搭建 使用 Vue CLI 快速初始化项目,安装必要依赖如 Vue Router、Vuex、Axios。 创建核心目录结构:components(通用组件)、views(页…

vue实现菜单调用

vue实现菜单调用

Vue 实现动态菜单的常见方法 基于路由配置生成菜单 Vue Router 的路由配置可以天然转化为菜单结构,适合权限与路由绑定的系统: // router/index.js const route…

vue 移动端实现签名

vue 移动端实现签名

Vue 移动端签名实现方法 在移动端实现签名功能,可以通过HTML5的Canvas结合触摸事件完成。以下是具体实现步骤: 使用Canvas绘制签名 安装vue-signature-pad插件或直接使…

vue按钮实现截屏

vue按钮实现截屏

Vue 按钮实现截屏的方法 在 Vue 项目中实现截屏功能可以通过多种方式完成,以下是几种常见的方法: 使用 html2canvas 库 安装 html2canvas 库: npm ins…

vue实现全局遮罩层

vue实现全局遮罩层

实现全局遮罩层的方法 在Vue中实现全局遮罩层可以通过多种方式完成,以下是几种常见的实现方法: 使用Vue组件创建遮罩层 创建一个遮罩层组件,通过全局注册或动态挂载的方式实现全局调用。以下是一个简单…