VUE 兄弟组件之间传值

兄弟组件

第一种
子 B
<template>
	<input @input='handleInput' :value='value'>
</template>

<script>
export default{
	props:{
		value:{
			type:[String,Number],
			default:''
		}
	},
	methods:{
		handleInput(e){
			const val = e.target.value
			this.emit('input',val)
		}
	}
}
</script>
子 C
<template>
	<div>{{val}}</div>
</template>

<script>
export default{
	props:{
		value:{
			type:[String,Number],
			default:''
		}
	}
}
</script>
父 A
<template>
  <div class="home">
    <h-b @input='handleInput'/>
    <h-c :value = 'val' />
  </div>
</template>

<script>

export default {
  name: "Home",
  data() {
    return {
      val: ""
    };
  },
  components: {
    hB:()=>import("@/components/B.vue"),
    hC:()=>import("@/components/C.vue"),
  },
  methods:{
      handleInput(val){
          this.val = val
      }
  }
};
</script>
第二种
bus.js
import Vue from 'vue'
const bus=new Vue()
export default bus
子 A
<template>
	<div>
		<button @click='emitMessage'>传给兄弟组件信息</button>
	</div>
</template>
<script>
// 引入 公共实例文件 bus.js
	import bus from './bus.js'
	export default{
		data(){
			return{
				title:'子组件A'
			}
		},
		methods:{
		//需要传值用 methods方法
			emitMessage(){
				// 兄弟组件接受 theMessage 的 this.title 值
				bus.$emit('theMessage',this.title)
			}
		}
	}
</script>
子 B
<template>
	<div>
		<h1>{{title}}</h1>
	</div>
</template>
<script>
// 引入 公共实例文件 bus.js
	import bus from './bus.js'
	export default{
		data(){
			return{
				title:'子组件B'
			}
		},
		mounted(){
		//需要传值用 mounted 
			bus.$on('theMessage',res=>{
				console.log(res)
				this.title = res	//经过子组件A的传值,此时显示的数据为子组件A的title 而不是子组件B的title
			})
		}
	}
</script>
父 App
<template>
	<div>
		<A/>
		<B/>
	</div>
</template>
<script>
// 引入 子组件 A和B
	import A from './views/A.vue'
	import B from './views/B.vue'
	export default{
		components:{
			A,
			B
		}
	}
</script>
第三种
Bus.js
import Vue from 'vue'
const bus=new Vue()
export default bus
main.js
import bus from './bus'

Vue.prototype.$bus=bus
子 A
<template>
	<div>
		<button @click='emitMessage'>传给兄弟组件信息</button>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				title:'子组件A'
			}
		},
		methods:{
		//需要传值用 methods方法
			emitMessage(){
				// 兄弟组件接受 getMessage 的 this.title 值
				this.$bus.$emit('getMessage',this.title)
			}
		}
	}
</script>
子 B
<template>
	<div>
		<h1>{{title}}</h1>
	</div>
</template>

<script>
	export default{
		data(){
			return{
				title:''
			}
		},
		mounted(){
		//需要传值用 mounted 
			this.$bus.$on('getMessage',data=>{
				this.title = data	
			})
		}
	}
</script>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值