Vue组件传值

本文介绍了Vue中组件间的通信方式,包括props从父组件向子组件传递,子组件通过$emit向父组件发送消息,以及兄弟组件间利用事件总线$bus进行通信,还有provide/inject用于后代组件获取祖先组件的数据。示例代码详细展示了父子、兄弟及后代组件之间的数据传递过程。
组件之间的传值?

在vue中,父子组件的关系可以总结为prop向下传递,事件向上传递。父组件通过prop给子组件下发数据,子组件通过事件给父组件发送信息。

img

  • 父组件传值给子组件,通过props属性进行传递。
  • 子组件给父组件传值,通过的是$emit方法,第一个参数是自定义事件的名字,第二个参数是传递过来的值,如果传递过来的值很多,可以使用对象的方法,把它们都写在第二个参数中。
  • 兄弟组件传值,在vue原型上定义一个新的实例,然后采用emit和emit和emiton这两个方法进行获取传递过来的值。
  • 给后代组件传值,provide和inject方法。
<!-- App.vue -->
<template>
  <div id="App">
    <Father></Father>
  </div>
</template>

<script>
import Father from  '@/components/test/Father'
export default {
  name: 'App',
  comments:{
    Father
  }
}
</script>
<!-- Father.vue -->
<template>
  <div class="father">
    <h1>父亲组件</h1>
    <Children :count="count" @sayLove="getLove"></Children>
    <span>子组件向父组件传过来的值----{{mylove}}</span>
    <Brother></Brother>
  </div>
</template>

<script>
import Brother from '@/components/test/Brother'
import Children from '@/components/test/Children'
export default {
  provide(){
    return{
      father:this //给后代接受
    }
  },
  data(){
    return{
      count:1,
      mylove:""
    }
  },
 comments:{
   Children,
   Brother
 },
  methods:{
    getLove(e){
      console.log(e);
      this.mylove=e;
    }
  }
}
</script>
<!-- Children.vue -->
<template>
  <div class="children">
    <h2>儿子组件</h2>
    <span>父亲组件传过来的值--{{count}}</span>
    <Grandson></Grandson>
    <button @click="sayLove">表达爱意</button>
  </div>
</template>

<script>
import Grandson from '@/components/test/Grandson'
export default {
  props:['count'],
  comments:{
    Grandson
  },
  methods:{
    sayLove(){
      this.$emit('sayLove','I love you')
      this.$bus.$emit('sayLoveToBro','I love you brother')
    }
  }
}
</script>
<!-- Brother.vue -->
<template>
    <div>
      <h2>兄弟组件</h2>
    </div>
</template>

<script>

export default {
  created () {
    this.$bus.$on('sayLovToBro',this.getlove)
  },
  methods:{
    getlove(e){
      console.log("兄弟组件",e)
    }
  }

}
</script>
<!-- Grandson.vue -->
<template>
  <div>
    <h3>孙子组件</h3>
    <span>爷爷给的值----{{count}}</span>
  </div>
</template>

<script>
export default {
  inject:['father'],
  data(){
    return{
      count:this.father.count
    }
  }
}
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值