前端开发那些事儿Vue 面试题及答案

手写 Vue 响应式框架

2020-09-20  本文已影响0人  阿畅_
vue.gif

手写一个简版的 Vue,实现 Vue 双向绑定,解析 v-model 指令

源码地址

  1. 把 data 中的数据变成响应式数据,拥有 get set 方法
  2. $el
  3. $options
  4. $data

最终效果

vue-demo.gif
<div id="app">
  <div>{{msg}}</div>
  <div v-text="count"></div>
  <input type="text" v-model="count">
</div>
const vm = new Vue({
  el: '#app',
  data: {
    count: 1,
    msg: 'hello Vue',
  }
})
console.log(vm)

实现 Vue

class Vue {
  // options 
  constructor(options) {
    this.$options = options || {}
    this.$data = options.data || {}
  
    // 获取DOM 元素,这里可能传递的是字符串
    this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el

    // 把 data 中的成员转换成 getter 和 setter 并注入到 Vue 实例中
    this._proxyData(this.$data)
  }

  // 代理数据
  _proxyData(data) {
    // 遍历所有的 data 属性
    Object.keys(data).forEach(d => {
      Object.defineProperty(this, d, {
        enumerable: true, // 可枚举
        configurable: true, // 可配置
        get() {
          return data[d]
        },
        set(newVal) {
          // 如果新的值和就的值相等,不需要重新赋值
          if (newVal === data[d]) return
          data[d] = newVal
        }
      })
    })
  }
}
<script src="./js/Vue.js"></script>
<script>
  let vm = new Vue({
    el: '#app',
    data: {
      msg: 'learn Vue',
      count: 100
    }
  })
  console.log(vm)
</script>

Observer

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

  // 遍历所有的属性
  walk(data) {
    // 判断 data 是否是对象
    if (!data || typeof data !== 'object') return

    // 遍历 data 对象所有属性
    Object.keys(data).forEach(key => {
      this.defineReactive(data, key, data[key])
    })
  }

  // 定义响应式数据
  defineReactive(obj, key, val) {
    // 如果 val 是对象,把对象类型数据转换成响应式数据
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get() {
        return val
      },
      // 使用箭头函数改变 this 的指向
      set: (newVal) => {
        if (newVal === val) return
        val = newVal
        // 当前属性重新 set 的时候,如果是 Object 类型,让里面的属性变成响应式数据
        this.walk(val)
        // 发送通知
      }
    })
  }
}

解释几个地方意思

  1. 这里的 为什么要传第三个参数, get 时返回 val, 不直接使用 obj[key]
defineReactive(obj, key, val) {
// 如果 val 是对象,把对象类型数据转换成响应式数据
Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  get() {
    return val
  },
  1. 直接赋值 val 为什么可以

Compile

Dep (dependency) 收集依赖

class Dep {
  constructor() {
    // 存储所有的观察者
    this.subs = []
  }

  // 添加观察者
  addSub(sub) {
    if (sub && sub.update) {
      this.subs.push(sub)
    }
  }

  // 发布通知
  notify() {
    this.subs.forEach(sub => {
      sub.update()
    })
  }
}

Watcher 观察者

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

    // 当前的 Watcher 对象记录到 Dep 类的静态属性 target 中
    // 触发 get 方法,在 get 方法中会调用 addSub
    Dep.target = this
    this.oldValue = vm[key]
    // 防止重复添加
    Dep.target = null
  }

  // 当数据发生变化的更新视图
  update() {
    let newValue = this.vm[this.key]
    if (newValue === this.oldValue) return
    // 调用回调函数,更新视图
    this.cb(newValue)
  }
}

实现双向绑定

// 处理 v-model 指令
modelUpdater(node, key, value) {
  node.value = value
  new Watcher(this.vm, key, (newValue) => {
    node.value = newValue
  })

  // 双向绑定
  node.addEventListener('input', () => {
    this.vm[key] = node.value
  })
}

最后的效果

watcher.gif
上一篇 下一篇

猜你喜欢

热点阅读