父传子通信

父组件传值给子组件 props
在开发中很常见的就是 父子组件之间通信,比如父组件有一些数据,需要子组件来进行展示:
这个时候我们可以 通过props来完成组件之间的通信;
什么是Props呢?

props是你可以在组件上注册 一些自定义的attribute;
父组件给这些 attribute赋值,子组件通过attribute的名称获取到对应的值;

props有两种常见的用法:

方式一:字符串数组,数组中的字符串就是attribute的名称;
方式二:对象类型,对象类型我们可以在指定attribute名称的同时,指定它需要传递的类型、是否是必须的、
默认值等等;

基本用法:字符串数组

<template>
<div>
<!-- :age 为了传递数字24所以需要使用v-bind绑定 -->
<child name="张三" :age="24"></child>
</div>
</template>

<script>
import Child from "./Child.vue";
export default {
components: { Child },
data() {
return {};
},
};
</script>

<style scoped></style>
<template>
<div>
<h3>我是子组件</h3>
<button>{ { typeof name }}——{ { name }}</button>
<button>{ { typeof age }}——{ { age }}</button>
</div>
</template>

<script>
export default {
// 数组方式
props: ["name", "age"],
};
</script>

<style scoped></style>

猜你喜欢

转载自blog.csdn.net/ALong_it/article/details/125754066