vue组件之间通讯的方式

1.父子组件传值($parent / $ref)

父组件
<template>
  <div>
    <div>{{msg}}</div>
    <child ref="children"></child>
    <button @click="change">点击改变子组件值</button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      fatherMsg: 'Welcome'
    }
  },
  methods: {
    change() {
      this.$ref.children.message = '父改子值'
    }
  }
}
</script>
子组件
<template>
  <div>
    <span>{{message}}<!-- 父改子值 --> </span>
    <p>获取父组件的值为:  {{parentVal}}</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      message: 'Vue'
    }
  },
  computed:{
    parentVal(){
      return this.$parent.fatherMsg;
    }
  }
}
</script>

2.全局事件传值($emit / $on)

3.【重要】祖孙组件传值($attrs)

A是B组件的父组件,B是C组件的父组件。想要组件A直接给C组件传递数据

祖组件
<template>
  <div class="section">
    <Father :sendGrandSon="sendGrandSon" :sendSon="sendSon" @change1="changFromSon"  @chang2="changFromGrandSon"></Father>
  </div>
</template>

<script>
  export default {
    name: 'Grandfather',
    data() {
      return {
        msg: '我是祖',
        sendSon:'传给子',
        sendGrandSon:'传给孙'
      }
    },
    methods(){
    	changFromSon(value){
    		console.log('子传值过来',value)//我是子
    	}changFromGrandSon(value){
    		console.log('孙传值过来',value)//我是孙啊
    	}
    }
  }
</script>
父组件
<template>
  <div>
    <Son v-bind="$attrs" v-on="$listeners"></Son>
  	<el-button @click="click">给父发消息</el-button>
  </div>
</template>

<script>
  export default {
    name: 'Father',
    props:['sendSon'],
    data() {
      return {
        msg: '我是祖'
      }
    },
    methods(){
    	click(){
    		this.$emit('changFromSon','我是子')
   		}
   	}
  }
</script>
孙组件
<template>
	<div>
  		<div class="section">我是孙</div>
  		<el-button @click="click">给爷爷发消息</el-button>
	</div>
</template>

<script>
  export default {
    name: 'Son',
    created(){
    	//这里只能接收到sendGrandSon。因sendSon在父组件(中间层)被接收掉了
    	console.log(this.$attrs)
    },
    methods(){
    	click(){
    		this.$emit('changFromGrandSon','我是孙')
   		}
   	}
  }
</script>

注意:

祖孙传值的参数,不能在父组件(中间层)使用props接受参数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值