vue父子组件通讯-数据传递

父子组件

概念:A组件中调用B组件,那么A组件就是父组件,B组件就是子组件
:父组件中通过import的方式导入子组件,并在components属性中注册,然后父组件就可以用标签调用子组件。

 <!-- 父组件 -->
<template>
  <div>
    <h1>我是父组件!</h1>
    <child></child>
  </div>
</template>

<script>
import Child from '../components/child.vue'
export default {
  components: {Child},
}
</script>
 <!-- 子组件 -->
<template>
  <h3>我是子组件!</h3>
</template>

<script>
</script>

父组件 → 子组件:props

子组件的props选项能够接收来自父组件数据。没错,仅仅只能接收,props是单向绑定的,即只能父组件向子组件传递,不能反向。而传递的方式也分为两种:
①静态传递
父组件在子组件标签中加上一个自定义的属性,子组件中通过props选项声明一个相同的属性接受父组件传递的数据。

 <!-- 父组件 -->
<template>
  <div>
    <h1>我是父组件!</h1>
    <child message="我是子组件一!"></child>  //通过自定义属性传递数据
  </div>
</template>

<script>
import Child from '../components/child.vue'
export default {
  components: {Child},
}
</script>
<!-- 子组件 -->
<template>
  <h3>{{message}}</h3>
</template>
<script>
  export default {
    props: ['message']   //声明一个自定义的属性
  }
</script>

②动态传递
动态数据可以用 v-bind 来实现。通过v-bind绑定props的自定义的属性,传递去过的就不是静态的字符串了,它可以是一个表达式、布尔值、对象等等任何类型的值。

 <!-- 父组件 -->
<template>
  <div>
    <h1>我是父组件!</h1>
    
    <!-- 这是一个 JavaScript 表达式而不是一个字符串。-->
    <child v-bind:message="a+b"></child>

    <!-- 用一个变量进行动态赋值。-->
    <child v-bind:message="msg"></child>
  </div>
</template>

<script>
import Child from '../components/child.vue'
export default {
  components: {Child},
  data() {
    return {
      a:'我是子组件二!',
      b:112233,
      msg: '我是子组件三!'+ Math.random()
    }
  }
}
</script>
 <!-- 子组件 -->
<template>
  <h3>{{message}}</h3>
</template>
<script>
  export default {
    props: ['message']
  }
</script>

子组件 → 父组件:$emit

vm.$emit( event, arg )
$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。

 <!-- 父组件 -->
<template>
  <div>
    <h1>{{title}}</h1>
    <child @getMessage="showMsg"></child>
  </div>
</template>

<script>
  import Child from '../components/child.vue'
  export default {
    components: {Child},
    data(){
      return{
        title:''
      }
    },
    methods:{
      showMsg(title){
       this.title=title;
      }
  }
  }
</script>
 <!-- 子组件 -->
<template>
  <h3>我是子组件!</h3>
</template>
<script>
  export default {
    mounted: function () {
      this.$emit('getMessage', '我是父组件!')
    }
  }
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值