Vue 组件之间数据传递的几种方式:
一. 父组件传子组件,使用props
//父组件
<template>
<div class="app-container">
<div class="box">
<Children :msg="message" ></Children> ///Children为子组件,将信息传给子组件
</div>
</div>
</template>
//父亲的信息export default {
data(){
return{
message:'123112',
userinfo:{name:'wsc',age:18},
}
},//子组件定义接收的自定义属性 export default { props:['msg'] }//在儿子组件中调用 <template> <div class="left-container"> <h3>Children 组件</h3> <p>message的值为{{msg}}</p> </div> </template>
二.子组件传父组件,使用$emit派发事件,
//子组件 methods:{ add(){ this.count++ //将值传给countChange this.$emit('count',this.count) } }//父组件 <template> <div class="app-container"> <h1>父组件</h1> <div class="box"> //通过@countChange接收子组件传过来的值,并赋给getCount方法 <Children @count='getCount'></Children> </div> </div> </template>methods:{ //获取数据 getNewCount(val){ this.countFromSon=val } }
三.其他
1.bus总线,不支持响应式
(1)main.js定义一个空的 Vue 实例
Vue.prototype.$bus = new Vue()(2)发送方
methods:{ send(row){ this.$bus.$emit('reject',row) } }(3)接受方
mounted() { this.$bus.$on('reject',(row)=>{ this.info=row }) }
2.window.parent
传入: window.parent.参数名
window.parent.函数名(参数1,参数2,…)
接受: window.参数名
window.函数名=(参数1,参数2,…)=>{
函数执行
}
3.ref
//传输 </template> <div> <a-button @click='handleEvent(record)'>{{ text }}</a-button> <Event ref='eventForm' @ok='eventFormOk'></Event> </div> </template> handleEvent(record) { this.$refs.eventForm.edit(record) },//接受<Event>界面
methods: { edit(record) { console.log(record) //接受到的数据 }, }
4.Vuex状态管理器(参考vue公共方法传参,实时刷新数据)