当前位置:首页 > 编程笔记 > 正文
已解决

Vue组件间传值

来自网友在路上 157857提问 提问时间:2023-10-22 23:29:45阅读次数: 57

最佳答案 问答题库578位专家为你答疑解惑

一、父传子

子组件中定义一个props,用来取出父组件传来的值

<script>export default {props:['msg'] //子组件定义props}
</script>

在父组件中对子组件的自定义属性绑定父组件的变量

<template><div class="parent">//子组件,绑定data中需要传送的值<Children :msg="message"></Children></div>
</template><script>
import Children from '../components/Children'export default {name: 'Parent',components: {Children},data() {return {message:'hello world'
}
},
}
</script>
 二、子传父

使用自定义事件,在父组件中给子组件绑定一个处理函数

<template><div class="parent"><Children @numChange = 'getNewNum'></Children></div>
</template><script>
import Children from '../components/Children'export default {data(){return {numFromSon:0}},methods:{getNewNum(val){this.countFromSon = val} }
</script>

子组件中使用$emit出发父组件中的函数进行传参

export default {data(){return {num 0}},methods:{count(){this.count +=1this.$emit('numChange',this.count)}}
}
三、兄弟组件间传值

采用事件总线eventBus,可以理解为在组件之间建立一个中转站

1.创建一个新的eventBus实例

import Vue from 'vue'const eventBus = new Vue() //创建Vue实例:eventBusexoprt default eventBus //暴露

2.在各组件中引入eventBus

import eventBus form '../eventBus.js'

3.使用$emit传参

eventBus.$emit('sendMsg','Hello World')

4.使用$on接受参数

eventBus.$on('sendMeg',(msg)=>{console.log(msg)}
)

总结:多练

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Vue组件间传值":http://eshow365.cn/6-21994-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!