vue组件之间的传值

父组件向子组传值
父组件

<!--:placeholder是想子组件传值的属性,可以自定义-->
<!--searchText此事件名必须要跟子组件传递过来的事件名一样-->
<SearchComponents @searchText='getChildData' :placeholder="startText" />
import SearchComponents from '@/components/SearchComponents.vue'
export default{
	name:'Home',
	components:{//注册组件
		SearchComponents
	},
	data(){
		return{
			startText:'向子组件传值'
		}
	},
	methods:{
	//这样就可以接受到子组件传递过来的值
		getChildData(e){
			console.log(e);
		}
	}
}

子组件

<div class="web">
		<div class="search">
		<!--:placeholder属性要跟父组件中的一样,不然不会报错-->
			<input type="text" 
			:placeholder="keyword"
			 v-model.trim="searchText">
		</div>
		<i class="iconfont icon-sousuo search-icon" @touchstart='searchData'></i>
	</div>
//通过props来接受父组件传递过来的值
export default{
	name:'search',
	//验证父组件穿过来的值
	props:{
		keyword: {
				type: String,//声明传入的类型
				default: '请输入关键字',//默认显示
				validator:function(value){
					return value//返回传入的值
				}
		},
	}
	//不需要认证父组件传过来的值
	props:["keyword"],
	data(){
		searchText:''
	},
	methods:{
		searchData(){
		//子组件通过$emit方法向父组件传递,searchText就是父组件接受时触发的事件
			this.$emit('searchText',this.searchText);
		}
	}
}

通过$emit 和 $on
这种方法通过一个空的Vue实例作为中央事件总线(事件中心),用它来触发事件和监听事件,巧妙而轻量地实现了任何组件间的通信,包括父子、兄弟、跨级组件之间的传值

 //新建bus  src/bus.js 
import Vue from 'vue'
export default new Vue( )

组件B向组件C传值

<template>
	<div @click="changB">
		组件B
	</div>
</template>
<script>
//引入中间件bug
	import bug from "@/bus.js";
	export default{
		name:'B',
		methods:{
			changB(){
			//bug也可以在main.js中注册,这样就不用每个组件进行引入
			//main.js   
			/*
			import bug from '@/bus.js';
			Vue.prototype.bug = bug;
			使用办法一样
			*/
			
				bug.$emit('brotherB','兄弟组件B传值给兄弟组件C')
			}
		},
		
	}
</script>

组件C接受组件B传过来的值
在接收参数的组件中也要引入bug.js

<template>
	<div @click="changeC">
		组件C
	</div>
</template>
<script>
	import bug from "@/bus.js";
	export default{
		methods:{
			changeC(){
				this.$bug.$emit('brotherC','组件C向组件B传值')
			}
		},
		//mounted钩子函数里面获取组件B传过来的值
		mounted(){
			bug.$on('brotherB',res=>{
				console.log(res)
			})
		}
	}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值