Skip to content

Commit

Permalink
update vue-tips
Browse files Browse the repository at this point in the history
  • Loading branch information
ccforward committed Jun 18, 2017
1 parent 21918f9 commit 5d2009f
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions Blog/62.vue.js-tips.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,88 @@ demo:
[https://ccforward.github.io/demos/vue-tips/select.html](https://ccforward.github.io/demos/vue-tips/select.html)


### 私有属性

如下代码

```js
data: {
name: 'name',
_name: 'name'
},
mounted() {
console.log(this.name, this._name);
}
```

结果输出为 "name" undefined

这是因为 以 _ 或者 $ 开头的属性只能 Vue 自身使用

[demo](https://codepen.io/ccforward/pen/BZqrNj)

## 用 debounce 延迟计算 watch 属性

debounce 去抖 尤其适合在输入这种高频的操作中实时计算属性值

```js
data: {
text: '',
inputing: false
},
watch: {
text: _.debounce(function () {
this.inputing = false
}, 1000)
}
```

顺手写个简单的 v-debounce 指令, 如下:

```js
const debounce = (fn, delay) {
let timer = null
return function () {
clearTimeout(timer)
timer = setTimeout(_ => {
fn.apply(this, arguments)
}, delay)
}
}

directive.debounce = debounce

function directive (el, binding) {
if (binding.value !== binding.oldValue) { // change debounce only if interval has changed
el.oninput = directive.debounce(_ => {
el.dispatchEvent(new Event('change'))
}, parseInt(binding.value) || 500)
}
}
module.exports = directive
```

Vue.js 中使用 v-debounce:

```html
<input v-debounce="delay" v-model="text" />
<p> {{text}} </p>
```

```js
import debounce from './debounce.js'
export default {
data () {
return {
text: 'some words',
delay: 500
}
},
directives: {debounce}
}
```





Expand Down

0 comments on commit 5d2009f

Please sign in to comment.