vue2 + ts 子组件怎么接收父组件传值
时间: 2023-12-24 17:47:43 浏览: 99
在 Vue2 中使用 TypeScript,可以通过 Props 定义接收父组件传值的属性。具体步骤如下:
1. 在子组件的 props 选项中定义需要接收的属性,例如:
```typescript
@Component({
props: {
title: String,
count: {
type: Number,
default: 0
}
}
})
export default class ChildComponent extends Vue {
// ...
}
```
2. 在父组件中通过 v-bind 指令将数据传递给子组件,例如:
```html
<template>
<div>
<child-component :title="title" :count="count"></child-component>
</div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import ChildComponent from './ChildComponent.vue';
@Component({
components: {
ChildComponent
}
})
export default class ParentComponent extends Vue {
title: string = 'Hello';
count: number = 10;
}
</script>
```
在上面的例子中,父组件中的 title 和 count 数据通过 v-bind 指令传递给了子组件的 title 和 count 属性。
3. 在子组件中使用 props 对象中定义的属性,例如:
```typescript
@Component
export default class ChildComponent extends Vue {
@Prop() title!: string;
@Prop({ default: 0 }) count!: number;
// ...
}
```
在上面的例子中,子组件通过 @Prop 装饰器定义了 title 和 count 属性,并在组件中使用它们。
注意:在 TypeScript 中使用 Vue,需要安装 `@vue/cli-plugin-typescript` 插件,并在 `tsconfig.json` 中添加 `"allowSyntheticDefaultImports": true` 选项。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)