Fork me on GitHub

Vue 杂记

vue 监听数组长度变化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var vm = new Vue({
el: 'body',
data: {
list: []
},
computed: {
length () {
return this.list.length
}
},
watch: {
list: {
deep: true,
handler (newValue, oldValue) {
console.log(newValue.length)
}
}
}
})

vue 监听对象变化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var vm = new Vue({
el: 'body',
data: {
items: {}
},
computed: {
isEmpty () {
return Object.keys(this.items).length === 0
}
},
watch: {
items: {
deep: true,
handler (newValue, oldValue) {
this.isEmpty = Object.keys(newValue).length === 0
}
}
}
})

错误处理

renderError

1
2
3
4
5
6
7
8
9
10
new Vue({
render (h) {
throw new Error('oops')
},
renderError (h, err) {
return h('pre', {
style: { color: 'red' }
}, err.stack)
}
}).$mount('#app')

errorCaptured

1
2
3
4
5
6
7
Vue.component('error-boundary', {
template: '<div><slot></slot></div>',
errorCapture: (err, vm, info) => {
console.log('We have an error')
return false
}
})

errorHandler & warnHandler

1
2
3
4
5
6
7
8
9
10
11
12
13
Vue.config.errHandler = function (err, vm, info) {
console.log(
`Error: ${err.toString()}
info: ${info}`
)
}

Vue.config.warnHandler = function (msg, vm, trace) {
console.log(
`Warn: ${msg}
Trace: ${trace}`
)
}

window.onerror

1
2
3
window.onerror = function (msg, source, line, column, error) {
// ...
}

减少重复

重复代码:

1
2
3
4
5
6
7
8
9
10
data () {
return {
internalValue: deepClone(this.value)
}
},
watch: {
value () {
this.internalValue = deepClone(this.value)
}
}

使用computed减少重复:

1
2
3
4
5
6
7
computed: {
internalValue () {
return this.value || this.value === 0
? [].concat(this.value)
: []
}
}

重复代码:

1
2
3
4
5
6
7
8
created () {
this.fetchUserList()
},
watch: {
searchText () {
this.fetchUserList()
}
}

使用immediate watcher减少重复:

1
2
3
4
5
6
watch: {
searchText: {
handler: 'fetchUserList',
immediate: true
}
}