当前位置:首页 > JavaScript

js实现vue

2026-01-31 14:37:26JavaScript

使用原生JavaScript实现Vue核心功能

Vue的核心功能包括数据响应式、模板编译和虚拟DOM。以下是使用原生JavaScript模拟Vue核心功能的实现方法。

数据响应式系统

通过Object.defineProperty实现数据劫持,当数据变化时通知依赖更新:

js实现vue

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()
      }
    })
  }
}

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

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

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

实现编译器

简单的模板编译器,将模板中的插值表达式替换为实际数据:

js实现vue

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) {
    const exp = RegExp.$1.trim()
    this.update(node, exp, '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, exp)
      }
    })
  }

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

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

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

  update(node, exp, dir) {
    const updaterFn = this[dir + 'Updater']
    updaterFn && updaterFn(node, this.$vm[exp])

    new Watcher(this.$vm, exp, function(value) {
      updaterFn && updaterFn(node, value)
    })
  }

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

  htmlUpdater(node, value) {
    node.innerHTML = value
  }
}

实现Watcher

Watcher作为观察者,当依赖变化时执行更新:

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm
    this.key = key
    this.cb = cb

    Dep.target = this
    this.vm[this.key] // 触发getter,添加依赖
    Dep.target = null
  }

  update() {
    this.cb.call(this.vm, this.vm[this.key])
  }
}

实现Vue类

整合以上功能创建Vue类:

class Vue {
  constructor(options) {
    this.$options = options
    this.$data = options.data

    new Observer(this.$data)

    Object.keys(this.$data).forEach(key => {
      this.proxyData(key)
    })

    new Compiler(options.el, this)
  }

  proxyData(key) {
    Object.defineProperty(this, key, {
      get() {
        return this.$data[key]
      },
      set(newVal) {
        this.$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'
  }
})

// 修改数据
setTimeout(() => {
  app.message = 'Data changed!'
}, 1000)
</script>

这个实现包含了Vue的核心功能:数据响应式、模板编译和依赖收集。实际Vue.js的实现更加复杂,包括虚拟DOM、组件系统、生命周期等更多功能,但以上代码展示了Vue的核心原理。

标签: jsvue
分享给朋友:

相关文章

vue实现视窗

vue实现视窗

Vue 实现视窗功能 在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式: 监听浏览器窗口大小变化 使用 Vue 的 mounted…

vue实现单点

vue实现单点

Vue 实现单点登录(SSO)方案 单点登录(SSO)允许用户在多个相关但独立的系统中使用同一组凭证登录。以下是基于 Vue 的实现方案: 基于 OAuth2/OpenID Connect 的实现…

vue实现计时

vue实现计时

Vue 实现计时功能 在 Vue 中实现计时功能可以通过多种方式完成,以下是几种常见的方法: 使用 setInterval 实现基础计时器 通过 setInterval 和 clearInterv…

vue实现拖放

vue实现拖放

Vue 实现拖放功能 Vue 中实现拖放功能通常可以通过 HTML5 的原生拖放 API 或第三方库(如 vuedraggable)来实现。以下是两种方法的详细说明。 使用 HTML5 原生拖放 A…

vue实现登出

vue实现登出

实现Vue登出功能 登出功能通常涉及清除用户会话、令牌或本地存储的数据,并重定向到登录页面。以下是几种常见的实现方式: 清除用户令牌和状态 在Vuex的store中定义一个logout mutat…

vue实现订单

vue实现订单

Vue 实现订单功能 订单数据结构设计 订单数据通常包含以下字段: order: { id: String, // 订单ID userId: String,…