已解决
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%的人还看了
相似问题
- Tekton — 通过tekton-operator部署tekton组件
- vue3中使用全局自定义指令和组件自定义指令
- HarmonyOS ArkTS 基础组件的使用(四)
- 界面控件DevExpress WPF流程图组件,完美复制Visio UI!(一)
- Vue2系列 -- 组件自动化全局注册(require.context)
- 扩散模型实战(十一):剖析Stable Diffusion Pipeline各个组件
- django DRF认证组件示例
- MySQL内部组件与日志详解
- 前端新手Vue3+Vite+Ts+Pinia+Sass项目指北系列文章 —— 第五章 Element-Plus组件库安装和使用
- 修改el-radio-group样式,自定义单选组件
猜你感兴趣
版权申明
本文"Vue组件间传值":http://eshow365.cn/6-21994-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 简单的代码优化(后端)
- 下一篇: 关注用户信息卡片