双向数据绑定原理主要运用了发布订阅模式来实现的,通过Object.defineProperty对数据劫持,触发getter,setter方法。数据变化时通知订阅者watcher触发回调视图更新。主要有四个重要的角色:
写一个简易的vue代码,实例化Vue
<script type="module"> import { Vue } from "./vue.js " let vm = new Vue({ el: document.querySelector('#app'), data: { message: "Hello,luyu", num: "33" }, methods: { increase() { this.num++; }, } }) </script> <div id="app"> <h1>{{message}}</h1> <h2>{{num}}</h2> <input type="text" v-model="message"> <input type="text" v-model="num"> <button v-on:click="increase">【+】</button> </div>
在vue的原型对象添加_init
方法进行初始化,主要干这几件事:
options
,并声明$options
,$el
,$data
,$methods
this.$data
代理为 this
,这样我们直接就可以this.变量值
export function Vue(options = {}) { this._init(options) } Vue.prototype._init = function (options) { this.$options = options; //假设这里就是一个el,已经querySelector this.$el = options.el; this.$data = options.data; this.$methods = options.methods; // beforeCreate--initState--initData proxy(this, this.$data) //observer() observer(this.$data)//对data监听,对data中数据变成响应式 new Compiler(this); }
proxy接收两个参数,一个是this(vue实例化对象),一个是需要代理的对象(this.$data),举个例子来说就是不使用this. $options.message
了,直接使用 this.message
获取数据。主要通过Object.defineProperty数据劫持,触发属性的getter或者setter方法。当然数据为NaN时,则不继续执行,故需要写一个方法进行判断。
// 把this.$data 代理到 this function proxy(target, data) { Object.keys(data).forEach(key => { Object.defineProperty(target, key, { enumerable: true, configurable: true, get() { return data[key] }, set(newValue) { //需要考虑NaN的情况,故需要修改以下代码 // if (data[key] !== newValue) data[key] = newValue if (!isSameVal(data[key], newValue)) data[key] = newValue; }, }) }) } function isSameVal (val,newVal){ //如果新值=旧值或者新值、旧值有一个为NaN,则不继续执行 return val === newVal || (Number.isNaN(val)) && (Number.isNaN(newVal)) }
对data数据进监听,考虑到数据有嵌套,如果数据类型为object则需要递归循环遍历监听数据,一个非常出名的监听方法为defineReactive
,接收三个参数,一个数据data,一个属性key,一个数值data[key]。那么observer监听数据主要做了什么事?
function observer(data) { new Observer(data) } // 对data监听,把数据变成响应式 class Observer { constructor(data) { this.walk(data) } //批量对数据进行监听 walk(data) { if (data && typeof data === 'object') { Object.keys(data).forEach(key => this.defineReactive(data, key, data[key])) } } //把每一个data里面的数据收集起来 defineReactive(obj, key, value) { let that = this; this.walk(value);//递归 let dep = new Dep(); Object.defineProperty(obj, key, { configurable: true, enumerable: true, get() { // 4一旦获取数据,把watcher收集起来,给每一个数据加一个依赖的收集 //5num中的dep,就有了这个watcher console.log(Dep.target, 'Dep.target') Dep.target && dep.add(Dep.target) return value }, set(newValue) { if (!isSameVal(value, newValue)) { value = newValue; //添加的新值也不是响应式的,所以需要调用walk that.walk(newValue); //有了watcher之后,修改时就可以调用update方法 //6 重新set时就通知更新 dep.notify() } } }) } }
数据改变需要通知视图层进行更新,更新仅需要调用Watcher中的update方法,然后执行cb(视图更新回调函数)。Watcher干了啥事?
// watcher和dep的组合就是发布订阅者模式 // 视图更新 // 数据改变,视图才会更新,需要去观察 // 1 new Watcher(vm, 'num', () => { 更新视图上的num显示 }) class Watcher { constructor(vm, key, cb) { this.vm = vm; this.key = key; this.cb = cb;//试图更新的函数 Dep.target = this;//2.全局变量,放的就是Watcher自己 // console.log(vm[key], 'vm[key]') this.__old = vm[key];//3.一旦进行了这句赋值。就会触发这个值得getter,会执行Observer中的get方法 Dep.target = null; } //执行所有的cb函数 update() { let newVal = this.vm[this.key]; if (!isSameVal(newVal, this.__old)) this.cb(newVal) } }
属性变化可能是多个,所以就需要一个订阅器来收集这些订阅者。Dep主要完成什么工作?
// 每一个数据都要有一个 dep 的依赖 class Dep { constructor() { this.watchers = new Set(); } add(watcher) { console.log(watcher, 'watcher') if (watcher && watcher.update) this.watchers.add(watcher) } //7让所有的watcher执行update方法 notify() { console.log('333333') console.log(this.watchers, 'watchers') this.watchers.forEach(watc => watc.update()) } }
编译器主要的工作是递归编译#app下的所有节点内容。主要做了以下几件事:
初始化编译器流程图如下所示:
数据修改时,因为初始化已经对数据做了响应式处理,所以当修改数据时,首先会走observer中的get方法,由于初始化已经对该数据进行监听,添加了watcher,并且此时Dep.target为null,所以不会再次收集订阅者信息,而是去通知视图进行更新,走了set中的notify,notify去通知所有的watcher去执行update方法。流程图如下所示:
class Compiler { constructor(vm) { this.el = vm.$el; this.vm = vm; this.methods = vm.$methods; // console.log(vm.$methods, 'vm.$methods') this.compile(vm.$el) } compile(el) { let childNodes = el.childNodes; //childNodes为类数组 Array.from(childNodes).forEach(node => { if (node.nodeType === 3) { this.compileText(node) } else if (node.nodeType === 1) { this.compileElement(node) } //递归 if (node.childNodes && node.childNodes.length) this.compile(node) }) } //文本节点处理 compileText(node) { //匹配出来 {{massage}} let reg = /\{\{(.+?)\}\}/; let value = node.textContent; if (reg.test(value)) { let key = RegExp.$1.trim() // 开始时赋值 node.textContent = value.replace(reg, this.vm[key]); //添加观察者 new Watcher(this.vm, key, val => { //数据改变时的更新 node.textContent = val; }) } } //元素节点 compileElement(node) { //简化,只做v-on,v-model的匹配 if (node.attributes.length) { Array.from(node.attributes).forEach(attr => { let attrName = attr.name; if (attrName.startsWith('v-')) { //v-指令匹配成功可能是是v-on,v-model attrName = attrName.indexOf(':') > -1 ? attrName.substr(5) : attrName.substr(2) let key = attr.value; this.update(node, key, attrName, this.vm[key]) } }) } } update(node, key, attrName, value) { console.log('更新') if (attrName == "model") { node.value = value; new Watcher(this.vm, key, val => node.value = val); node.addEventListener('input', () => { this.vm[key] = node.value; }) } else if (attrName == 'click') { // console.log(this.methods,'key') node.addEventListener(attrName, this.methods[key].bind(this.vm)) } } }
元素节点中node.attributes如下:
//以下面代码为例 <input type="text" v-model="num">
reg.exec用来检索字符串中的正则表达式的匹配,每次匹配完成后,reg.lastIndex被设定为匹配命中的结束位置。
reg.exec传入其它语句时,lastIndex不会自动重置为0,需要手动重置 reg.exec匹配结果可以直接从其返回值读取
let reg=/jpg|jpg|jpeg/gi let str='jpg' if(reg.test(str)){ // true } if(reg.test(str)){ // false } if(reg.test(str)){ // true } if(reg.test(str)){ // false }
(/jpg|jpg|jpeg/gi).test(str) // true (/jpg|jpg|jpeg/gi).test(str) // true (/jpg|jpg|jpeg/gi).test(str) // true
测试字符串是否与正则表达式匹配
保存了最近1次exec或test执行产生的子表达式命中匹配。该特性是非标准的,请尽量不要在生产环境中使用它
用于检测字符串是否以指定的子字符串开始。如果是以指定的子字符串开头返回 true,否则 false,该方法对大小写敏感。
var str = "Hello world, welcome to the Runoob."; var n = str.startsWith("Hello");//true
地址:链接跳转