vue学习笔记(二)
组件化编码的流程
1.实现静态组件:抽取组件,使用组件实现静态页面效果
2.展示动态数据:
2.1. 数据的类型、名称是什么?
2.2. 数据保存在哪个组件?
3.交互——从绑定事件监听开始
组件的自定义事件
1、子组件向父组件传递数据的方式
(1)通过父组件给子组件传递函数类型的props实现:子给父传递数据
//App.vue
<School :getSchoolName="getSchoolName"/>
methods: {
getSchoolName(name){
console.log('App收到了学校名:',name)
},
}
//School.vue
<button @click="sendSchoolName">把学校名给App</button>
props:['getSchoolName'],
methods: {
sendSchoolName(){
this.getSchoolName(this.name)
}
},
(2)通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on)
//App.vue
<Student @atguigu="getStudentName"/>
getStudentName(name,...params){
console.log('App收到了学生名:',name,params)
this.studentName = name
},
//Student.vue
<button @click="sendStudentlName">把学生名给App</button>
sendStudentlName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888,900)
},
(3)通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref)
//App.vue
<Student ref="student" @click.native="show"/>
mounted() {
this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
// this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
},
//Student.vue
<button @click="sendStudentlName">把学生名给App</button>
sendStudentlName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888,900)
},
(2)解绑事件
//School.vue
<button @click="add">点我number++</button>
<button @click="unbind">解绑atguigu事件</button>
<button @click="death">销毁当前Student组件的实例(vc)</button>
add(){
console.log('add回调被调用了')
this.number++
}, //组件销毁后,add方法不会被销毁,依然可以被调用。他属于原生的DOM事件
unbind(){
this.$off('atguigu') //解绑一个自定义事件
// this.$off(['atguigu','demo']) //解绑多个自定义事件
// this.$off() //解绑所有的自定义事件
},
death(){
this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。
}
(3)总结
1. 一种组件间通信的方式,适用于:子组件 ===> 父组件
2. 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
3. 绑定自定义事件:
第一种方式,在父组件中:<Demo @atguigu="test"/> 或 <Demo v-on:atguigu="test"/>
第二种方式,在父组件中:
<Demo ref="demo"/>
......
mounted(){
this.$refs.xxx.$on('atguigu',this.test)
}
若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法。
this.$refs.student.$once('atguigu',this.getStudentName) 或者 <Demo @atguigu.once="test"/>
4. 子组件触发自定义事件:this.$emit('atguigu',数据)
5. 解绑自定义事件this.$off('atguigu')
6. 组件上也可以绑定原生DOM事件,需要使用native修饰符。(默认是自定义事件)
<Student ref="student" @click.native="show"/>(这样会在当前组件下去调用show)
7. 注意:通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!(不写的话 this指向触发事件的那个vc)