点击勘误issues (opens new window),哪吒感谢大家的阅读

要使vue支持ts写法,我们需要用到vue-property-decorator,这个组件完全依赖于vue-class-componet

首先安装:

npm i -D vue-property-decorator
1

@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})

@PropSync和@Prop用法类似,二者区别在于:

@PropSync装饰器接受两个参数:

propName: string类型,表示父组件传递过来的属性名;

options: PropOptions | Constructor[] | Constructor 与@Prop中第一个参数一致;
1

@PropSync会生成一个新的计算属性

注意,使用@PropSync的时候是要在父组件配合.sync使用的

import { Vue, Component, PropSync } from 'vue-property-decorator'
 
@Component
export default class YourComponent extends Vue {
  @PropSync('name', { type: String }) syncedName!: string
}
1
2
3
4
5
6

以上代码等同于:

export default {
  props: {
    name: {
      type: String,
    },
  },
  computed: {
    syncedName: {
      get() {
        return this.name
      },
      set(value) {
        this.$emit('update:name', value)
      },
    },
  },
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

来看一个父子组件的例子:

// 父组件
<template>
  <div class="PropSync">
    <h1>父组件</h1>
    <h2>{{name}}</h2>
    <Child :name.sync="name"></Child>
  </div>
</template>
 
<script lang='ts'>
import { Vue, Component } from 'vue-property-decorator';
import Child from './Child.vue';
 
@Component({components: { Parent }})
export default class ParentPage extends Vue {
  private name = '父组件名字';
}
</script>
 
// 子组件
<template>
  <div class="child">
    <h1>子组件:</h1>
    <h2>syncedName:{{ syncedName }}</h2>
    <button @click="changeName">修改name</button>
  </div>
</template>
 
<script lang="ts">
import { Component, Vue, PropSync} from 'vue-property-decorator';
 
@Component
export default class ChildComponent extends Vue {
  @PropSync('name', { type: String }) syncedName!: string; // 用来实现组件的双向绑定,子组件可以更改父组件穿过来的值
 
  changeName(): void {
    this.syncedName = '子组件修改过后的syncedName!'; // 双向绑定,更改syncedName会更改父组件的name
  }
}
</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
29
30
31
32
33
34
35
36
37
38
39
40
上次更新: 2/16/2022, 6:00:01 PM