vue3+ts中的传参

1.子组件如何做:

这里以一个对象数组类型的参数为例

(1)子组件中定义要传过来的参数,该参数要有一个类型约定(interface),这里要导出是因为父组件要用到该接口:

export interface ColumnProps {
  id: number;
  title: string;
  avatar: string;
  description: string;
}

(2)子组件中的props属性如何定义该传过来的参数:

props:{
   list: Array as PropType<ColumnPros[]>,
   required:true  
}
import { defineComponent, PropType } from 'vue'

说明:

  • 这个props中不能直接使用Array as ColumnProps[],因为Array是一个数组的构造函数,不是一个类型,所以不能断言成一个类型
  • vue中PropType的用法:
    • 接受一个泛型,可以将一个array的构造函数返回传入的泛型类型
    • 可以把一个构造函数断言成一个类型

2.父组件如何调用子组件:

(1)引入子组件及子组件定义的接口(interface)

import ColumnList, { ColumnProps } from './components/ColumnList.vue'

模拟传给子组件的数据:

const testData: ColumnProps[] = [
  {
    id: 1,
    title: 'test1的专栏',
    description: '这是test1的专栏,有一段非常有意思的简介,可以更新以下哦',
    avatar:
      'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1827281934,1605450328&fm=15&gp=0.jpg'
  },
  {
    id: 2,
    title: 'test2的专栏',
    description: '这是test2的专栏,有一段非常有意思的简介,可以更新以下哦',
    avatar:
      'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1827281934,1605450328&fm=15&gp=0.jpg'
  }
]

(2)setup中设置data:

  components: { ColumnList },
  setup () {
    return {
      list: testData
    }
  }

(3)页面中调用:

<column-list :list="list"></column-list>

3.效果:

即可在页面中出现:

原文地址:https://www.cnblogs.com/codexlx/p/13942286.html