【vue】父子组件通信

一、 父组件向子组件通信

1. prop 传递数据

我们用的最多方式,可以通过 Prop 向子组件传递数据。
用一个形象的比喻来说,父子组件之间的数据传递相当于自上而下的下水管子,只能从上往下流,不能逆流。这也正是 Vue 的设计理念之单向数据流。而 Prop 正是管道和管道之间的一个衔接口,这样(水)数据才能向下流.

// parent.vue

<template>
  <div>
    <Child :name="name" />
  </div>
</template>

<script>
import Child from '@/components/child'
export default {
  components: {
    Child
  },
  data() {
    return {
      name: '顾鸟'
    }
  }
}
</script>

// child.vue

<template>
  <div>{{ name }}</div>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      default: ''
    }
  }
}
</script>

2. $refs 获取子组件实例,进而调用子组件方法或者直接修改子组件属性

调用子组件的方法 this.$refs.child.fromParent(‘我从父组件传递过来’)

直接修改子组件的 data 数据 this.$refs.child.message2 = ‘啦啦啦’

// child.vue

<template>
  <div id="child">
    <div>{{ message1 }}</div>
    <div>{{ message2 }}</div>
  </div>
</template>
<script>
export default {
  name: 'child',
  data() {
    return {
      message1: '',
      message2: ''
    }
  },
  methods: {
    fromParent(msg) {
      this.message1 = msg
    }
  }
}
</script>

// parent.vue

<template>
  <div id="parent">
    <button @click="toChild">click</button>
    <child ref="child"></child>
  </div>
</template>
<script>
import child from '@/components/child.vue'
export default {
  name: 'parent',
  components: { child },
  methods: {
    toChild() {
      this.$refs.child.fromParent('我从父组件传递过来')
      this.$refs.child.message2 = '啦啦啦'
    }
  }
}
</script>

二、子组件向父组件通信

1. $emit 触发父组件的方法或传递数据

通过 $emit 进行触发,第一个参数为父组件监听的事件名,后续参数为父组件方法的参数

// child.vue

<template>
  <div id="child">
    <button @click="tryToParent">click</button>
  </div>
</template>
<script>
export default {
  name: 'child',
  methods: {
    tryToParent() {
      this.$emit('toParent', '我从子组件传来')
    }
  }
}
</script>

// parent.vue

<template>
  <div id="parent">
    <child @toParent="fromChild"></child>
  </div>
</template>
<script>
import child from '@/components/child.vue'
export default {
  name: 'parent',
  components: { child },
  methods: {
    fromChild(msg) {
      console.log(msg)
    }
  }
}
</script>

三、其他方法

  1. Vuex

    官方推荐,Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式,适合处理复杂项目。

  2. a t t r s 、 attrs、 attrslisteners

    a t t r s 和 attrs和 attrs 和 listeners 属性像两个收纳箱,一个负责收纳属性,一个负责收纳事件,都是以对象的形式来保存数据

  3. provide/inject

    这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。如果你熟悉 React,这与 React 的上下文特性很相似。
    provide 和 inject 主要为高阶插件/组件库提供用例。并不推荐直接用于应用程序代码中。

不忘初心

参考链接:
https://www.cnblogs.com/vickylinj/p/10877765.html
https://blog.csdn.net/qq_37288477/article/details/86630428
https://www.cnblogs.com/yangshifu/archive/2018/08/22/9518528.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值