组件之间的通信

本文介绍Vue.js中父子组件之间的通信方式,包括父组件向子组件传递数据的方法及子组件通过自定义事件向父组件发送消息的技术实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备阶段

先写子组件componentA.vue:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
  export default {
    name : 'componentA',
    data : function() {
      return {
        msg: 'component a'
      }
    }
  }
</script>

<style scoped>
  h1, h2 {
    font-weight: normal;
    color: #42b983;
  }
</style>

在父组件(App.vue)中导入上面的组件:

<template>
  <div id="app">
    <h1>{{ title }}</h1>
    <component-a></component-a>   <!--将驼峰式的写法要写成左边那样-->
    ....
  </div>
</template>

<script>
  import componentA from './components/componentA.vue' //*

  export default {
    name: 'hello',
    components: { componentA },  //*
    data: function() {
      return {
        ....
      }
    },
    methods: {
        .....
    }
  }
</script>

<style>
    ....
</style>

那么子组件如何收到父组件的信息呢?

父组件里面:

<component-a fathertell="hello, my son"></component-a>

子组件里面:要加上props这个属性,并且里面的变量名要表示成字符串的形式,并且在子组件里面可以访问到这个变量

  export default {
    name : 'componentA',
    props: ['fathertell'],
    data : function() {
      return {
        msg: 'hello from component a'
      }
    }
  }

子组件向父组件传递参数的情况

父组件里:父组件中使用v-on绑定自定义事件,如这样v-on:child-tell="listenToMySon",其中”child-tell“就是我的自定义事件,而”listenToMySon“就是事件处理函数

<p>Child tells: {{ childWords }}</p>
<component-a fathertell="hello, my son" v-on:child-tell="listenToMySon"></component-a>
  export default {
    name: 'hello',
    components: { componentA },
    data: function() {
      return {
        ...
        childWords : ''    //这个与显示的{{ childWords }}对应
      }
    },
    methods: {
      listenToMySon : function(msg) {   //自定义事件的事件处理函数
          this.childWords = msg;
      }
    }
  }

子组件里:子组件当然是要触发这个自定义事件了,在这里我让点击按钮时触发

<button @click="onClickMe">ComponentA say</button>
methods: {
  onClickMe: function() {
    this.$emit('child-tell', this.msg);  //参数:自定义事件 传给父组件的参数(这个与父组件的事件处理                                    //函数的参数对应)
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值