Vue组件间通信的六种方式

向右看齐 2024-03-16 16:59 88阅读 0赞

第一种(props)

使用场景:父子组件通信

如果父组件给子组件传递函数:本质是子组件给父组件传递

如果父组件给子组件传递非函数:本质是父组件给子组件传递

  1. //只接收:
  2. props: ['todos']
  3. //限制类型:
  4. props: {
  5. name: String}
  6. //限制类型、限制必要性、指定默认值:
  7. props: {
  8. name: {
  9. type: String,
  10. required: true,
  11. default: 'zhangsan'
  12. }
  13. }

路由的props

书写形式:对象,布尔值(只能接收params参数),函数形式

第二种(自定义事件)

使用场景:子组件给父组件传递数据

在父组件中给子组件绑定自定义事件(事件的回调在父组件中)

  1. // 给Student绑定自定义事件
  2. <Student @atguigu="getStudentName"/>
  3. this.$refs.student.$on('atguigu', this.getStudentName)
  4. // 触发Student组件身上的atguigu事件
  5. this.$emit('atguigu', '回传的数据')

第三种(全局事件总线$bus)

使用场景:万能

Vue.prototype.$bus = this

fc4c5294929b48c0b98251cb0abf3118.png

第四种(pubsub-js)

发布与订阅,(在React种使用较多)

使用场景:万能

第五种(插槽)

使用场景:父子组件通信(向子组件指定位置插入html结构)

默认插槽、具名插槽、作用域插槽

  1. <!--父组件-->
  2. <List :todos="todos">
  3. <!--定义子组件的结构和外观-->
  4. <template slot-scope="{todo, $index}">
  5. <span :style="{color: todo.isComplete ? 'green' : 'red'}">{
  6. {
  7. $index}}---{
  8. {
  9. todo.text}}</span>
  10. </template>
  11. </List>
  12. <!--子组件-->
  13. <li v-for="(item, index) in todos" :key="index">
  14. <slot :todo="item" :$index="index"></slot>
  15. </li>

第六种(Vuex)

使用场景:万能

e027ad87e53d4d3191cd2001db60783a.png

发表评论

表情:
评论列表 (有 0 条评论,88人围观)

还没有评论,来说两句吧...

相关阅读