组件间通信
父组件有一些数据,需要子组件来进行展示:
这个时候我们可以通过 props 来完成组件之间的通信;
- Props 是你可以在组件上注册一些自定义的 attribute;
- 父组件给这些 attribute 赋值,子组件通过 attribute 的名称获取到对应的值;
#
props 数组字符串数组,数组中的字符串就是 attribute 的名称
通过App.vue传递给组件数据
<template> <div> <show-message title="哈哈哈" content="我是哈哈哈"></show-message> <show-message title="呵呵呵" content="我是呵呵呵"></show-message> </div></template>
<script> import ShowMessage from "./ShowMessage.vue";
export default { components: { ShowMessage, }, };</script>
封装ShowMessage.vue组件
<template> <div> <h2>组件展示的title:{{title}}</h2> <p>组件展示的content: {{content}}</p> </div></template>
<script> export default { props: ["title", "content"], };</script>
#
props 对象对象类型我们可以在指定 attribute 名称的同时,指定它需要传递的类型、是否是必须的、默认值等等
fu
<template> <div> <h2>组件展示的title:{{ title }}</h2> <p>组件展示的content: {{ content }}</p> </div></template><script> export default { props: { // 指定类型 title: String, // 指定类型,同时指定是否必选、默认值 content: { type: String, require: true, default: "哈哈哈", }, }, };</script>