我是靠谱客的博主 生动火龙果,这篇文章主要介绍vue组件通信(子传父),现在分享给大家,希望可以做个参考。

1.通过props方式的传递

2.通过this.$emit()方式传递

在父组件绑定自定义事件,@sendStuent='getStuentName'

注意:组件上绑定原生DOM事件,需要使用native修饰符

3.通过ref方式传递

父组件

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template> <div id="app"> {{msg}} <!-- 第一种方式 --> <School :getSchoolName="getSchoolName"/> <Student @sendStuent='getStuentName'/> <my-student ref="student"></my-student> </div> </template> <script> import School from './components/School.vue' import Student from './components/Student.vue' import MyStudent from './components/MyStudent.vue' export default { name: 'App', components: { School, Student, MyStudent, }, data(){ return{ msg:'父组件的数据' } }, methods:{ getSchoolName(schoolName){ console.log("App接受的学校名:",schoolName) }, // ...params用于接收其他参数 getStuentName(studentName,...params){ console.log("App接受的学生名:",studentName,params) }, getStuentAge(age,...params){ console.log("App接受的学生名:",age,params) } }, mounted(){ this.$refs.student.$on('sendStuentAge',this.getStuentAge) } } </script>

子组件(props方式)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template> <div class="child"> <p>子组件1</p> <p>{{name}}</p> <button @click="sendSchoolName">把子组件的学校名给父组件</button> </div> </template> <script> export default { // eslint-disable-next-line vue/multi-word-component-names name:'School', props:['getSchoolName'], data(){ return{ name:'尚硅谷' } }, methods:{ sendSchoolName(){ this.getSchoolName(this.name) } } } </script>

子组件(this.$emit方式)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<template> <div class="child"> <p>子组件2</p> <p>{{name}}</p> <button @click="sendStudentName">把子组件的学生名给父组件</button> <button @click="unbind">解绑sendStuent自定义事件</button> </div> </template> <script> export default { // eslint-disable-next-line vue/multi-word-component-names name:'Student', data(){ return{ name:'张三' } }, methods:{ sendStudentName(){ this.$emit('sendStuent',this.name,11,22,33) }, // 解绑自定义事件 unbind(){ this.$off('sendStuent') //解绑一个 // this.$off(['sendStuent','demo']) //解绑多个 // this.$off() //所有自定义事件全部解绑 }, death(){ this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件完全不奏效 } } } </script>

子组件(ref方式)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<template> <div class="child"> <p>子组件3</p> <p>{{age}}</p> <button @click="sendStudentAge">把子组件的学生年龄给父组件</button> </div> </template> <script> export default { // eslint-disable-next-line vue/multi-word-component-names name:'Student', data(){ return{ age:'20' } }, methods:{ sendStudentAge(){ this.$emit('sendStuentAge',this.age,11,22,33) } } } </script>

最后

以上就是生动火龙果最近收集整理的关于vue组件通信(子传父)的全部内容,更多相关vue组件通信(子传父)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部