vue双向数据绑定

1.数据响应式原理

  主要是利用Object.defineProterty()来自定义Object的getter,setter

function observe(value, cb) {
    Object.keys(value).forEach((key) => defineReactive(value, key, value[key] , cb))
}

function defineReactive (obj, key, val, cb) {
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        get: ()=>{
            /*....依赖收集等....*/
         
            return val
        },
        set:newVal=> {
            val = newVal;
            cb();/*订阅者收到消息的回调*/
        }
    })
}

class Vue { constructor(options) { this._data = options.data; observe(this._data, options.render) } } let app = new Vue({ el: '#app', data: { text: 'text', text2: 'text2' }, render(){ console.log("render"); } }) 通过observe函数对app.data上的每一个key和value都设定getter和setter。当value改变的时候触发setter,就会触发render这个函数。
响应式的目的就达成,如果是视图更新的话我们通过监听dom的input事件来触发数据更新

响应式原理:
每个组件实例都对应一个 watcher 实例,它会在组件渲染的过程中把“接触”过的数据 property 记录为依赖。之后当依赖项的 setter 触发时,会通知 watcher,从而使它关联的组件重新渲染
2.动态生成的输入框的只规定数字规则
	<div v-for="(item,index) in arr">
			<input type="text"  @change="blurMethods(item.a,index)" v-model="item.a">
		</div>
		<button @click="add">添加</button>

  

 blurMethods(value,index){
		  console.log(value)
		  if(!this.ceshi(value)){
			  this.arr[index].a=''
		  }
	  },

  



  

posted @ 2021-03-03 18:18  本园一帅  阅读(61)  评论(0编辑  收藏  举报