v-model属性在render函数中是下面这样的
on: { "input": function($event) { if ($event.target.composing) return; $set(obj, "name", $event.target.value) } }
意思也就是,第一次input事件的时候,调用$set,而set
function set (target, key, val) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (key in target && !(key in Object.prototype)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val }
注意红色字体,所以用v-model的话,没必要再在初始化的时候用$set绑定属性,但是注意紫色字体,不要在input事件之前给obj.name赋值,否则不会响应,非要赋值就提前用$set赋值
如果v-model=“obj.prop.name”,那么$set中的参数target就是obj.prop