Vue 使用筆記
- 2019 年 11 月 8 日
- 筆記
記錄開發過程中使用 Vue 時遇到的一些問題和解決辦法。
watch 對象的屬性
data: { a: 100, msg: { channel: "音樂", style: "活潑" } }, watch: { a(newval, oldVal) { console.log("new: %s, old: %s", newval, oldVal); } }
watch: { msg: { handler(newValue, oldValue) { console.log(newValue) }, // 深度監聽 deep: true } }
監聽對象內的某一具體屬性,可以通過 computed
做中間層來實現:
computed: { channel() { return this.msg.channel } }, watch:{ channel(newValue, oldValue) { console.log('new: %s, old: %s', newval, oldVal) } }
判斷 data 中的對象是否為空
1、利用 jQuery
的 isEmptyObject
:
$.isEmptyObject(data.list);
實現源碼:
isEmptyObject: function(obj) { var name; for (name in obj) { return false; } return true; }
2、獲取到對象中的屬性名,存到一個數組中,通過判斷數組的 length
來判斷此對象是否為空:
var arr = Object.getOwnPropertyNames(data); alert(arr.length == 0); // true
ES6:
var arr = Object.keys(data.list); alert(arr.length == 0); // true
3、轉化為 json
字元串,再判斷該字元串是否為 {}
:
var b = JSON.stringify(data) == "{}"; alert(b); // true
References: