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、利用 jQueryisEmptyObject

$.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: