vue2 组件传值

艺达 发布于:2022-07-21 10:12:08

子组件

<template>
	<div class="m-soso">
		<button type="button" class="btn" @click="$emit('search',value)">搜索</button>
		<div class=" box">
			<img src="../../assets/images/667.png" alt="" class="ico">
			<input type="search" class="inp" @input="change" name="word" :value="value" placeholder="请输入你想搜索的内容" autocomplete="off"/>
		</div>
	</div>
</template>
<script>
	export default {
		name: "So",
		components: {},
		model:{
		  prop: 'value',  // 绑定的props属性,这里是'nameFromFather'
		  event: 'changes'    // 触发父组件中v-model绑定的属性发生改变的方法,名称自取
		},
		props: {
			value: {
				type: String,
				default: "",
			}
		},
		data() {
			return {
			};
		},
		mounted() {
		},
		methods: {
			 change(e){
			        //this.$emit('调用的方法即model中的event','子组件input的值')
			        this.$emit('changes',e.target.value)
			      }
		},
	};
</script>
<style scoped>

.m-soso {
		overflow: hidden;
		margin-bottom: 30px;
		box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
		position: relative;
		border-radius: 5px;
		background-color: #fff;
	}
	
	.m-soso .ico {
		position: absolute;
		left: 15px;
		top: 18px;
		width: 26px;
	}
	
	.m-soso .box {
		overflow: hidden;
		padding: 0 0 0 50px;
		border: none;
	}
	
	.m-soso .inp {
		width: 99%;
		border: none;
		height: 65px;
		outline: none;
		font-size: 20px;
	}
	
	.m-soso .btn {
		height: 65px;
		float: right;
		background-color: #4190f7;
		color: #FFFFFF;
		border: none;
		width: 120px;
		font-size: 19px;
		cursor: pointer;
		transition: .5s;
		outline: none;
	}
	.m-soso .btn:hover {
		background-color: #0c61d1;
	}
	.m-soso .btn:active{
		background-color: #4190f7;
	}
</style>



页面中使用

<So @search="search" v-model="sovalue" @changes="changes2"></So>
<menuBar @changes="changes" ref="menubar"></menuBar>


ref操作子组件

changes2(res){
				console.log('change',res)
				if(!res){
					this.$refs.menubar.clear() 
					// 执行menuBar组件里面的clear方法
				}
			},


menuBar 子组件接收事件

	mounted () {
	  this.list_old = this.list
	  this.$on('clear',()=>{
	      this.clear();
	  });
	},
	methods: {
		clear(){
		    // 清理操作
		},
	}


觉得有用请点个赞吧!
1 1194