点击勘误issues (opens new window),哪吒感谢大家的阅读
要使vue支持ts写法,我们需要用到vue-property-decorator,这个组件完全依赖于vue-class-componet
首先安装:
npm i -D vue-property-decorator
1
@Watch(path: string, options: WatchOptions = {})
@Watch装饰器接受两个参数:
- path: string类型,表示需要被监听的属性名;
- options?: WatchOptions = {} 包含两个属性:
- immediate?: boolean 监听开始后是否立即调用该回调函数;
- deep?: boolean 表示是否深度监听
使用Demo如下:
<template>
<div class="watchPage">
<h1>child: {{child}}<input type="text" v-model="child"/></h1>
<h1>person.name: {{person.name}}<input type="text" v-model="person.name"/></h1>
</div>
</template>
<script lang="ts">
// 从vue-property-decorator中引入Component、Watch、Vue
import { Component, Vue, Watch } from 'vue-property-decorator';
@Component
export default class WatchPage extends Vue {
child = ''
person = {
name: 'zxx'
}
@Watch('child')
onChildChanged(val: string, oldVal: string) {
console.log(val, oldVal);
}
@Watch('person', { immediate: true, deep: true })
onPersonChanged(val: Person, oldVal: Person) {
console.log(val, oldVal);
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
以上script中代码等同于:
export default {
data() {
return {
child: '',
person: {
name: 'zxx'
}
}
}
watch: {
child: [
{
handler: 'onChildChanged',
immediate: false,
deep: false,
},
],
person: [
{
handler: 'onPersonChanged',
immediate: true,
deep: true,
}
],
},
methods: {
onChildChanged(val, oldVal) {
console.log(val ,oldVal);
},
onPersonChanged(val, oldVal) {
console.log(val ,oldVal);
}
},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34