vue自定义事件

绑定

父组件:App.vue 子组件:Student.vue

方式一: $emit

<template>
	<div class="student">
		<button @click="sendStudentlName">把学生名给App</button>
	</div>
</template>

<script>
	export default {
		name:'Student',
		data() {
			return {
				name:'张三',
				sex:'男',
				number:0
			}
		},
		methods: {
			sendStudentlName(){
				//触发Student组件实例身上的atguigu事件
				this.$emit('sendName',this.name,1,2,3)
			}
		},
	}
</script>
<template>
	<div class="app">
		<h1>{{msg}},学生姓名是:{{studentName}}</h1>

		<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
		< <Student @sendName="getStudentName" @demo="m1"/> 

		<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
	
	</div>
</template>

<script>
	import Student from './components/Student'
	import School from './components/School'

	export default {
		name:'App',
		components:{School,Student},
		data() {
			return {
				msg:'你好啊!',
				studentName:''
			}
		},
		methods: {
			getStudentName(name,...params){
				console.log('App收到了学生名:',name,params)
				this.studentName = name
			}
		},
	}
</script>

方式二

//父组件App.vue
...
<Student ref="student"/>
...
mounted() {
    this.$refs.student.$on('sendName',this.getStudentName) //绑定自定义事件
    // this.$refs.student.$once('atguigu',this.getStudentName) //只触发一次
},

解绑

//子组件
this.$off('sendName')
posted @ 2021-08-17 17:06  至安  阅读(675)  评论(0编辑  收藏  举报