详细教学vue子组件和祖父组件的通讯

导语:
想象大家在开发的过程中总会遇到子组件和祖父组件的通讯问题,而且不知道怎么解决,这篇文章教会大家。

1,子组件向祖父组件传值

son是father的子组件,father是grandfather的子组件。

1,son组件

<son @click="clickson"/>
<script >
export default {
     
     
methods: {
     
     
	clickson (args) {
     
     
		this.$emit('father', args) //args要传的参数
	}
}
}
</script>

2,father组件

<father >
	<son @father=“clickfather” />
<father>
<script >
export default {
     
     
methods: {
     
     
	clickfather (args) {
     
     
		this.$emit('grandfather', args) //args要传的参数
	}
}
}
</script>

3,grandfather组件

<grandfather >
	<father @grandfather=“clickgrandfather”/>
<grandfather>
<script >
export default {
     
     
methods: {
     
     
	clickgrandfather () {
     
     
		console.log(args)//args要传的参数
	}
}
}
</script>

这样就可以son组件执行grandfather组件的函数。

2,祖父组件向子组件传值

1,grandfather组件

<template>
  <div class="grandfather">
    <father :msg1="msg1" />
  </div>
</template>

<script>f
import father from './father'
export default {
     
     
  components: {
     
     father},
  data () {
     
     
    return {
     
     
      msg1: '小米粥'
    }
  }
}
</script>

2,father组件

<template>
  <div class="father">
    <son :msg1="msg1" />
  </div>
</template>s

<script>
import son from './son'
export default {
     
     
  props: ['msg1'],
  components: {
     
     son},
}
</script>

3,son组件

<template>
<div class="son">
  <p>{
   
   {msg1}}</p>
</div>
</template>

<script>
export default {
     
     
  props: ['msg1']
}
</script>

补充
在这里插入图片描述
微信搜索【web小馆】,回复全栈博客项目,即可获取项目源码和后续的实战文章教程。每天用最简单朴实的语言,潜移默化的提升你的计算机基础知识和前端技术。小米粥,一个专注的web全栈工程师,我们下期再见!

在这里插入图片描述
node后台

猜你喜欢

转载自blog.csdn.net/gitchatxiaomi/article/details/108810950
今日推荐