# 31.Vue组件之间传值

# 1.父组件向子组件传值

props传递数据原则: 单向数据流

1).组件内部通过props接收传递过来的值 (数据接收方)

Vue.component('menu-item', {
  props: ['title'],               // 注意: props传递过来的数据原则上是不做修改的
  template: '<div>{{ title }}</div>'
})
1
2
3
4

2).父组件通过属性将值传递给子组件 (数据传递方)

<menu-item title="来自父组件的数据"></menu-item>
<menu-item :title="title"></menu-item>
1
2

3).props属性名规则

  • 在props中使用驼峰形式, html中需要使用短横线的形式

  • 字符串形式的模板中没有这个限制

Vue.component('menu-item', {
  // 在Javascript 中是驼峰式的
  props: ['menuTitle'],
  template: '<div> {{ menuTitle}} </div>'
})

<!-- 在html中是短横线方式的 -->
<menu-item menu-title="nihao"></menu-item>
1
2
3
4
5
6
7
8

4).props属性值类型

  • 字符串 String
  • 数值 Number (注意这个不加: 是字符串类型)
  • 布尔值 Boolean (注意这个不加: 是字符串类型)
  • 数组 Array
  • 对象 Object

# 2.子组件向父组件传值

1).子组件通过自定义事件向父组件传递信息

<button v-on:click='$emit("enlarge-text")'>扩大字体</button>
1

2).父组件监听子组件的事件

<menu-item v-on:enlarge-text='fontSize += 0.1'></menu-item>
1

# 3.子组件向父组件传值 (带参数)

1).子组件通过自定义事件向父组件传递信息

<button v-on:click='$emit("enlarge-text", 5)'>扩大字体</button>
<!-- emlarge-text是自定义的   5 是要传递的参数 (多个参数使用对象形式进行传递) -->
1
2

2).父组件监听子组件的事件 (父组件通过$event接收参数)

<menu-item v-on:enlarge-text='fontSize += $event'></menu-item>
1

# 4.兄弟组件之间的传递

1).单独的事件中心管理组件间的通信

var eventHub = new Vue()
1

2).监听事件与销毁事件(接收数据方)

eventHub.$on('add-todo', ()=>{})  // 监听事件 参数一:事件名称(自定义)  参数二: 函数(业务)
eventHub.$off('add-todo')		 // 销毁事件 
1
2

3).触发事件(传递数据方)

eventHub.$emit('add-todo', id)  // 参数一: 兄弟组件的事件名称  参数二: 需要传递的数据
1
上次更新: 2020/10/27 下午11:58:10