我是靠谱客的博主 糟糕睫毛,这篇文章主要介绍vue父子传值,兄弟传值,子父传值详解,现在分享给大家,希望可以做个参考。

一、父组件向子组件传值

1.父组件.vue

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 父组件中 <template> <div> <Child ref="child" :title="value"/> </div> </template> <script> export default { data() { return { value: 'hello world!' } } } </script>

2.子组件.vue

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 父组件中 <template> <div> <span>{{title}}</span> </div> </template> <script> export default { props: { title: { type: String, default: '' } } } </script>

//title值为'hello world!

二、兄弟组件间传值还可以通过中间件Bus

$emit 传值

$on 接收

$off 删除传输事件

1.A组件.js

复制代码
1
this.$bus.$emit("flag",true)

2.B组件.js

复制代码
1
2
3
4
5
6
mounted() { this.$bus.$off('flag') this.$bus.$on('flag', data=> { this.flag= data }) }

三、子组件向父组件传值

1.父组件.js

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template> <div> <Child ref="child" @getTitle="getTitle"/> </div> </template> <script> import Child from './components/Child' export default { components: { Child }, data() { return { } }, method:{ getTitle(data){ console.log(data) } } } </script>

打印结果为 hello xuliting

2.子组件.js

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template> <div> <span>{{title}}</span> </div> </template> <script> export default { data() { return { title: 'hello xuliting' } }, mounted(){ this.getFun() }, method:{ getFun(){ this.$emit("getTiltle",this.title) } } } </script>

总结:

组件间也可以通过传递方法从而解决。例如父组件为A,子组件有B和C。

父组件A调用子组件B的方法定义为aFun,把aFun传递给子组件C即可

这是在父组件中的组件C进行方法传递

复制代码
1
<C :a-fun="aFun" />

引用的则是在组件C,通过props

复制代码
1
2
3
4
5
6
props: { aFun: { type: Function, default: () => function() {} } }

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注靠谱客的更多内容!

最后

以上就是糟糕睫毛最近收集整理的关于vue父子传值,兄弟传值,子父传值详解的全部内容,更多相关vue父子传值内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部