组件的自定义事件
1. 一种组件问通信的方式,适用于 子组件===>父组件
2.使用场量: A是父组件。B是子组件。B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
3.绑定自定义事件:
1.第一种方式,在父组件中: <Demo @atguigu-"test"/> 或<Demo v-on:atguigyu-"test"/>
2.第二种方式。在父组件中:
<Dome ref="demo"/>
mounted(){
this.$refs.xxx.$on("atguigu" ,this.test)
}
3.若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法。
4.触发自定义事件: this.$emit("atguigu" ,数据)
5.解绑自定义事件this.off(" atguigu')
6.组件上也可以绑定原生DOM事件,需要使用native修饰符。
7.注意:通过this. $refs.xxx.$on( 'atguigu' ,回调)绑定白定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!
实例:
app.vue
<template>
<div id="app">
<h2>xxx:{{name}}</h2>
<!--通过父组件给子组件绑定一个自定义事件实现:子给父传递数据 (第一种写法。使用@或v-on)-->
<School @atguigu="getSchoolName" />
<!--通过父组件给子组件绑定一个白定义事件实现: 子给父传递数据(第二种写法。使用ref)-->
<Student ref="student" />
</div>
</template>
<script>
import School from './components/School'
import Student from './components/Student'
export default {
name: 'App',
data() {
return {
name:""
}
},
components: {
School,
Student
},
methods: {
getSchoolName(name) {
console.log(name),
this.name=name
},
getStudentName(name,...params) {
console.log(name+" "+params),
this.name = name
}
},
mounted() {
//第二种写法。使用ref的
this.$refs.student.$on("atguigu", this.getStudentName)
}
}
</script>
<style scoped>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
background-color:#b6ff00;
}
</style>
School.vue
<template>
<div class="demo">
<div>{{schoolName}}</div>
<div>{{schoolAdress}}</div>
<button @click="SetShoolName">上传学校姓名</button>
</div>
</template>
<script>
export default {
name: 'School',
data() {
return {
schoolName: 'xuexiao',
schoolAdress: 'dizhi'
}
},
methods:{
SetShoolName() {
console.log("school:" + this.schoolName)
this.$emit("atguigu", this.schoolName)
}
}
}
</script>
<style scoped>
.demo{
background-color:royalblue;
}
</style>
Student.vue
<template>
<!--组件的结构-->
<div class="demo2">
<div>{{name}}</div>
<div>{{age}}</div>
<button @click="SetStudentName">上传学生姓名</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: "Alice",
age:"18"
}
},
methods: {
//触发Student组件实例身上的atguigu事件
SetStudentName() {
this.$emit("atguigu", this.name,100,200,300)
}
}
}
</script>
<style scoped>
.demo2{
background-color:greenyellow;
}
</style>
解绑
<template>
<!--组件的结构-->
<div class="demo2">
<div>{{name}}</div>
<div>{{age}}</div>
<button @click="SetStudentName">上传学生姓名</button>
<button @click="unbind">解绑</button>
</div>
</template>
<script>
export default {
name: 'Student',
data() {
return {
name: "Alice",
age:"18"
}
},
methods: {
//触发Student组件实例身上的atguigu事件
SetStudentName() {
this.$emit("atguigu", this.name,100,200,300)
},
unbind() {
//this.$off("atguigu") 解绑单个自定义事件
//this.$off(["atguigu","demo"]) 解绑多个自定义事件
this.$off() //解绑全部自定义事件
}
}
}
</script>