对于出学vue的开发者来说,v-bind这种绑定事件作为传参的手段是很常见的.
当然使用prop进行传参可能在某些情况下更有优势
在父组件中
<template>
<div>
<KeepAlive>
<Com :is="current" v-bind="userProps"></Com>
</KeepAlive>
</div>
</template>
<script setup lang= "ts">
import Com from './com1.vue'
import {reactive} from 'vue'
//这里声明了一个对象数据 userProps
const userProps = reactive(
{
id: 1,
name: 'John Doe',
email: 'john.doe@example.com'
}
);
</script>
声明了一组要传递的数据,数据源可能是json静态数据也可能是一组db fetch后的结果集
这里传递的时候使用v-bind方式传递
子组件接收并显示
<template>
{{ id }} -- {{ name }} -- {{ email }}
</template>
<script setup lang="ts">
import { defineProps } from 'vue'
interface UserPorps {
id: number
name: string
email: string
}
const props = defineProps<UserPorps>()
const {id, name ,email} = props
</script>
看下结果
ok其实到这里一切都还很简单.但是当我要传递一组数据的时候呢.
const userProps = ref([
{
id: 1,
name: 'John Doe',
email: 'john.doe@example.com'
},
{
id: 2,
name: 'Evan Doe',
email: 'Evan.doe@example.com'
},
{
id: 3,
name: 'good Doe',
email: 'good.doe@example.com'
},
]);
修改子组件
<template>
<ul>
<li v-for="item in props" :key="item.id">
{{ item.id }} - {{ item.name }} - {{ item.email }}
</li>
</ul>
</template>
<script setup lang="ts">
import { defineProps } from 'vue'
interface UserPorps {
id: number
name: string
email: string
}
const props = defineProps<UserPorps[]>()
</script>
没报错,语法正常
运行下:
没错TS+vue就是这么让你崩溃
看错误信息,是我们传递的数组类型在props中没有被识别
修改下类型.加一个别名users
const props = defineProps<{users: UserPorps[]}>()
替换下loop的数组name
<li v-for="item in users" :key="item.id">
保存下,文件没有报错,语法正确,再运行下
看下代码,父组件又报错了....
先说下修改的方法
将传递的绑定更换成:方式,绑定设置的别名
<Com :users="userProps"></Com>
运行下
怎么说呢,总结下,跟我在写react的时候差别很大,我原想向react那种随意的流畅的传递porps直接{...props}发一个结构 对象是不可能的
官方的介绍其实有点,嗯.我理解的不透测吧.
使用一个对象绑定多个 prop
如果你想要将一个对象的所有属性都当作 props 传入,你可以使用没有参数的 v-bind,即只使用
v-bind
而非:prop-name
。例如,这里有一个post
对象:
我天真的以为一个数组对象的porps也算做是一个对象的所有属性
单个参数或者多个props分别传可以
<ComponentA a = "y" b="x" c="z" />
只要你不嫌麻烦
优化的点放到一个对象里
就需要
const obj = {
a: "y",
b: "x",
c: "z"
}
<ComponentA v-bind="obj" />
而传递数组的数据的时候呢,又变成这样
const obj = [
{
a: "y",
b: "x",
c: "z"
},
{
a: "y1",
b: "x1",
c: "z1"
},
{
a: "y3",
b: "x3",
c: "z3"
},
]
<ComponentA :arr="obj" />
相应的配合TS, 在接受的时候也需要对应match上别名和接受数组类型的对象在props的定义中
const props = defineProps<{arr: UserPorps[]}>()
最后问题不可怕. 发现问题解决问题,了解问题原因不断成长.