Vue 2.0 偵聽器 watch屬性代碼詳解
用法
--------------------------------------------------------------------------------
先來看看官網(wǎng)的介紹:
官網(wǎng)介紹的很好理解了,也就是監(jiān)聽一個(gè)數(shù)據(jù)的變化,當(dāng)該數(shù)據(jù)變化時(shí)執(zhí)行我們的watch方法,watch選項(xiàng)是一個(gè)對(duì)象,鍵為需要觀察的表達(dá)式(函數(shù)),還可以是一個(gè)對(duì)象,可以包含如下幾個(gè)屬性:
handler ;對(duì)應(yīng)的函數(shù) ;可以帶兩個(gè)參數(shù),分別是新的值和舊的值,上下文為當(dāng)前Vue實(shí)例
immediate ;偵聽開始之后是否立即調(diào)用 ;默認(rèn)為false
sync ;波爾值,是否同步執(zhí)行,默認(rèn)false ;如果設(shè)置了這個(gè)屬性,當(dāng)數(shù)據(jù)有變化時(shí)就會(huì)立即執(zhí)行了,否則放到下一個(gè)tick中排隊(duì)執(zhí)行
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<p>{{message}}</p>
<button @click="test">測(cè)試</button>
</div>
<script>
var app = new Vue({
el:'#app',
data:{message:'hello world!'},
watch:{
message:function(newval,val){
console.log(newval,val)
}
},
methods:{
test:()=>app.message="Hello Vue!"
}
})
</script>
</body>
</html>
DOM渲染如下:

點(diǎn)擊測(cè)試按鈕后DOM變成了:

同時(shí)控制臺(tái)輸出:Hello Vue! hello world!
源碼分析
--------------------------------------------------------------------------------
Vue實(shí)例后會(huì)先執(zhí)行_init()進(jìn)行初始化(4579行)時(shí),會(huì)執(zhí)行initState()進(jìn)行初始化,如下:
function initState (vm) { //第3303行
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch && opts.watch !== nativeWatch) { //如果傳入了watch 且 watch不等于nativeWatch(細(xì)節(jié)處理,在Firefox瀏覽器下Object的原型上含有一個(gè)watch函數(shù))
initWatch(vm, opts.watch); //調(diào)用initWatch()函數(shù)初始化watch
}
}
function initWatch (vm, watch) { //第3541行
for (var key in watch) { //遍歷watch里的每個(gè)元素
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler); //調(diào)用createWatcher
}
}
}
function createWatcher ( //創(chuàng)建用戶watcher
vm,
expOrFn,
handler,
options
) {
if (isPlainObject(handler)) { //如果handler是個(gè)對(duì)象,則將該對(duì)象的hanler屬性保存到handler里面 從這里看到值可以是個(gè)對(duì)象
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
return vm.$watch(expOrFn, handler, options) //最后創(chuàng)建一個(gè)用戶watch
}
Vue原型上的$watch構(gòu)造函數(shù)如下:
Vue.prototype.$watch = function ( //第3596行
expOrFn, //監(jiān)聽的屬性,例如例子里的message
cb, //對(duì)應(yīng)的函數(shù)
options //選項(xiàng)
) {
var vm = this;
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {};
options.user = true; //設(shè)置options.user為true,表示這是一個(gè)用戶watch
var watcher = new Watcher(vm, expOrFn, cb, options); //創(chuàng)建一個(gè)Watcher對(duì)象
if (options.immediate) { //如果有immediate選項(xiàng),則直接運(yùn)行
cb.call(vm, watcher.value);
}
return function unwatchFn () {
watcher.teardown();
}
};
}
偵聽器對(duì)應(yīng)的用戶watch的user選項(xiàng)是true的,全局Watcher如下:
var Watcher = function Watcher ( //第3082行
vm,
expOrFn, //偵聽的屬性:message
cb, //對(duì)應(yīng)的函數(shù)
options,
isRenderWatcher
) {
this.vm = vm;
if (isRenderWatcher) {
vm._watcher = this;
}
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user; //用戶watch這里的user屬性為true
this.lazy = !!options.lazy;
this.sync = !!options.sync;
} else {
this.deep = this.user = this.lazy = this.sync = false;
}
this.cb = cb;
this.id = ++uid$1; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
this.expression = expOrFn.toString();
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else { //偵聽器執(zhí)行到這里,
this.getter = parsePath(expOrFn); //get對(duì)應(yīng)的是parsePath()返回的匿名函數(shù)
if (!this.getter) {
this.getter = function () {};
"development" !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get(); //最后會(huì)執(zhí)行g(shù)et()方法
};
function parsePath (path) { //解析路勁
if (bailRE.test(path)) {
return
}
var segments = path.split('.');
return function (obj) { //返回一個(gè)函數(shù),參數(shù)是一個(gè)對(duì)象
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
執(zhí)行Watcher的get()方法時(shí)就將監(jiān)聽的元素也就是例子里的message對(duì)應(yīng)的deps將當(dāng)前watcher(用戶watcher)作為訂閱者,如下:
Watcher.prototype.get = function get () { //第3135行
pushTarget(this); //將當(dāng)前用戶watch保存到Dep.target總=中
var value;
var vm = this.vm;
try {
value = this.getter.call(vm, vm); //執(zhí)行用戶wathcer的getter()方法,此方法會(huì)將當(dāng)前用戶watcher作為訂閱者訂閱起來
} catch (e) {
if (this.user) {
handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget(); //恢復(fù)之前的watcher
this.cleanupDeps();
}
return value
};
當(dāng)我們點(diǎn)擊按鈕了修改了app.message時(shí)就會(huì)執(zhí)行app.message對(duì)應(yīng)的訪問控制器的set()方法,就會(huì)執(zhí)行這個(gè)用戶watcher的update()方法,如下:
Watcher.prototype.update = function update () { //第3200行 更新Watcher
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) { //如果$this.sync為true,則直接運(yùn)行this.run獲取結(jié)果
this.run();
} else {
queueWatcher(this); //否則調(diào)用queueWatcher()函數(shù)把所有要執(zhí)行update()的watch push到隊(duì)列中
}
};
Watcher.prototype.run = function run () { //第3215行 執(zhí)行,會(huì)調(diào)用get()獲取對(duì)應(yīng)的值
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) { //如果是個(gè)用戶 watcher
try {
this.cb.call(this.vm, value, oldValue); //執(zhí)行這個(gè)回調(diào)函數(shù) vm作為上下文 參數(shù)1為新值 參數(shù)2為舊值 也就是最后我們自己定義的function(newval,val){ console.log(newval,val) }函數(shù)
} catch (e) {
handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
對(duì)于偵聽器來說,Vue內(nèi)部的流程就是這樣子
總結(jié)
以上所述是小編給大家介紹的Vue 2.0 偵聽器 watch屬性代碼詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
vue3內(nèi)嵌iframe的傳參與接收參數(shù)代碼示例
這篇文章主要給大家介紹了關(guān)于vue3內(nèi)嵌iframe的傳參與接收參數(shù)的相關(guān)資料,Vue項(xiàng)目中使用iframe及傳值功能相信有不少人都遇到過,需要的朋友可以參考下2023-07-07
vue結(jié)合v-for和input實(shí)現(xiàn)多選列表checkbox功能
在Vue中,可通過v-for指令和v-model實(shí)現(xiàn)多選列表功能,首先,使用v-for指令遍歷數(shù)組生成列表項(xiàng),每個(gè)列表項(xiàng)包含一個(gè)復(fù)選框,復(fù)選框的v-model綁定到一個(gè)數(shù)組變量,用于存儲(chǔ)選中的值,感興趣的朋友跟隨小編一起看看吧2024-09-09
在vue中使用Echarts利用watch做動(dòng)態(tài)數(shù)據(jù)渲染操作
這篇文章主要介紹了在vue中使用Echarts利用watch做動(dòng)態(tài)數(shù)據(jù)渲染操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07
vue實(shí)現(xiàn)數(shù)字動(dòng)態(tài)翻牌的效果(開箱即用)
這篇文章主要介紹了vue實(shí)現(xiàn)數(shù)字動(dòng)態(tài)翻牌的效果(開箱即用),實(shí)現(xiàn)原理是激將1到9的數(shù)字豎直排版,通過translate移動(dòng)位置顯示不同數(shù)字,本文通過實(shí)例代碼講解,需要的朋友可以參考下2019-12-12
Vue項(xiàng)目如何保持用戶登錄狀態(tài)(localStorage+vuex刷新頁面后狀態(tài)依然保持)
關(guān)于vue登錄注冊(cè),并保持登錄狀態(tài),是vue玩家必經(jīng)之路,這篇文章主要給大家介紹了關(guān)于Vue項(xiàng)目如何保持用戶登錄狀態(tài)的相關(guān)資料,localStorage+vuex刷新頁面后狀態(tài)依然保持,需要的朋友可以參考下2022-05-05

