js 實現(xiàn)watch監(jiān)聽數(shù)據(jù)變化的代碼
更新時間:2019年10月13日 10:58:21 作者:曾經(jīng)的水哥
這篇文章主要介紹了js 實現(xiàn)watch監(jiān)聽數(shù)據(jù)變化的代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
1.js
/**
* @desc 屬性改變監(jiān)聽,屬性被set時出發(fā)watch的方法,類似vue的watch
* @author Jason
* @study https://www.jianshu.com/p/00502d10ea95
* @data 2018-04-27
* @constructor
* @param {object} opts - 構(gòu)造參數(shù). @default {data:{},watch:{}};
* @argument {object} data - 要綁定的屬性
* @argument {object} watch - 要監(jiān)聽的屬性的回調(diào)
* watch @callback (newVal,oldVal) - 新值與舊值
*/
class watcher{
constructor(opts){
this.$data = this.getBaseType(opts.data) === 'Object' ? opts.data : {};
this.$watch = this.getBaseType(opts.watch) === 'Object' ? opts.watch : {};
for(let key in opts.data){
this.setData(key)
}
}
getBaseType(target) {
const typeStr = Object.prototype.toString.apply(target);
return typeStr.slice(8, -1);
}
setData(_key){
Object.defineProperty(this,_key,{
get: function () {
return this.$data[_key];
},
set : function (val) {
const oldVal = this.$data[_key];
if(oldVal === val)return val;
this.$data[_key] = val;
this.$watch[_key] && typeof this.$watch[_key] === 'function' && (
this.$watch[_key].call(this,val,oldVal)
);
return val;
},
});
}
}
// export default watcher;
2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>wathc</title>
</head>
<body>
<script src="./watch.js"></script>
<script>
let wm = new watcher({
data:{
a: 0,
b: 'hello'
},
watch:{
a(newVal,oldVal){
console.log(newVal, oldVal); // 111 0
}
}
})
wm.a = 111
</script>
</body>
</html>
3. 給vm.a 從新賦值 就能看到 newVal 和oldVal的變化
總結(jié)
以上所述是小編給大家介紹的js 實現(xiàn)watch監(jiān)聽數(shù)據(jù)變化的代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
您可能感興趣的文章:
- JS如何監(jiān)聽div的resize事件詳解
- JavaScript 監(jiān)聽組合按鍵思路及代碼實現(xiàn)
- JavaScript如何實現(xiàn)監(jiān)聽鍵盤輸入和鼠標(biāo)監(jiān)點擊
- NodeJS多種創(chuàng)建WebSocket監(jiān)聽的方式(三種)
- js實現(xiàn)無刷新監(jiān)聽URL的變化示例代碼詳解
- JavaScript監(jiān)聽鍵盤事件代碼實現(xiàn)
- 使用JS監(jiān)聽鍵盤按下事件(keydown event)
- javascript事件監(jiān)聽與事件委托實例詳解
- 如何用JS實現(xiàn)簡單的數(shù)據(jù)監(jiān)聽
相關(guān)文章
基于aotu.js實現(xiàn)微信自動添加通訊錄中的聯(lián)系人功能
這篇文章主要介紹了利用aotu.js實現(xiàn)微信自動添加通訊錄中的聯(lián)系人,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
javascript實現(xiàn)Email郵件顯示與刪除功能
這篇文章主要介紹了javascript實現(xiàn)Email郵件顯示與刪除功能,需要的朋友可以參考下2015-11-11
用Javascript檢查Adobe PDF插件是否安裝的實現(xiàn)代碼
用Javascript檢查Adobe PDF插件是否安裝的代碼2009-12-12
js/jquery控制頁面動態(tài)加載數(shù)據(jù) 滑動滾動條自動加載事件的方法
下面小編就為大家?guī)硪黄猨s/jquery控制頁面動態(tài)加載數(shù)據(jù) 滑動滾動條自動加載事件的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02

