组件的自定义事件
1.一种组件间通讯的方式,适应于:
子组件===》父组件
父组件
<template>
<div id="app">
<school @changeshow="changeshow"></school>
<student ref="studentref"></student>
</div>
</template>
<script>
import school from './components/school.vue'
import student from './components/student.vue'
export default {
name: 'App',
components: {
school, student
},
mounted () {
//第二种 ref 的方式
this.$refs.studentref.$on("show", (data) => {
console.log(data)
})
},
methods: {
//第一种 自定义事件
changeshow (index) {
console.log(index)
}
},
}
</script>
<style>
#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;
}
</style>
子组件
<template>
<div>
<div>我是student</div>
<button @click="toschool">点击 给school传值</button>
</div>
</template>
<script>
export default {
name: 'student',
props: {
msg: String
},
mounted () {
},
methods: {
toschool () {
//this.$bus.$emit('hello', "666")
this.$emit("show", "00000")
}
},
}
</script>
2.使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件回调在A中)
3.绑定自定义事件:
1.第一种方式,在父组件中:<Demo @atguigu=“test” />或者
2.第二种方式,在父组件中:
…
mounted(){
this.
r
e
f
s
.
d
e
m
o
.
refs.demo.
refs.demo.on(‘atguigu’,this.test)
}
3.若想让自定义事件只能触发一次,可以使用once修饰符,或
o
n
c
e
方
法
4.
触
发
自
定
义
事
件
:
t
h
i
s
.
once方法 4.触发自定义事件:this.
once方法4.触发自定义事件:this.emit(‘atguigu’,数据)
5.解绑自定义事件:this.
o
f
f
(
′
a
t
g
u
i
g
u
′
)
6.
组
件
上
可
以
绑
定
原
生
的
D
O
M
事
件
,
需
要
用
n
a
t
i
v
e
修
饰
符
7.
注
意
:
t
h
i
s
.
off('atguigu') 6.组件上可以绑定原生的DOM事件,需要用native修饰符 7.注意:this.
off(′atguigu′)6.组件上可以绑定原生的DOM事件,需要用native修饰符7.注意:this.refs.demo.$on(‘atguigu’,回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向的是子组件
兄弟组件传值
main.js
new Vue({
el:"#app",
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = this
}
}).$mount('#app')
兄弟组件 接收数据的哥哥
<template>
<div>
<div @click="dianwo">我是school</div>
</div>
</template>
<script>
export default {
name: 'school',
props: {
msg: String
},
mounted () {
// console.log('School',this)
this.$bus.$on('hello', (data) => {
console.log('我是School组件,收到了数据', data)
})
},
methods: {
},
beforeDestroy () {
this.$bus.$off("hello") //这里记得解绑
},
}
</script>
兄弟组件 传数据的弟弟
<template>
<div>
<div>我是student</div>
<button @click="toschool">点击 给school传值</button>
</div>
</template>
<script>
export default {
name: 'student',
props: {
msg: String
},
mounted () {
},
methods: {
toschool () {
this.$bus.$emit('hello', "666")
}
},
}
</script>
祖孙组件传值
provide inject 祖组件传值给 后代组件(爷爷给孙子传值)
1.祖组件里
setup(){
let car = reactive({name:‘奔驰’,price:‘20’})
provide(‘car’,car)
}
2.孙组件中
setup(){
let car = inject(‘car’)
console.log(car)
}