文章目录
1.父组件 传值 子组件 2.子组件 传值 父组件 3.兄弟组件之间的传值
1.父组件 传值 子组件
父组件:
<Header :msg='msg'></Header>
子组件:
props:['msg']
或 props:{ msg:数据类型 }
< template>
< div>
父组件
< Header :msg = ' msg' > </ Header>
</ div>
</ template>
< script type = " text/javascript" >
import Header from './Header'
export default {
data ( ) {
return {
msg : '这是数据'
}
} ,
components : {
Header
}
}
</ script>
< template>
< div>
子组件
< hr />
{{msg}}
</ div>
</ template>
< script type = " text/javascript" >
export default {
props : {
msg : String
}
}
</ script>
2.子组件 传值 父组件
子组件:
this.$emit("自定义事件名称",要传的数据);
父组件:
<Header @childInput='getVal'></Header>
methods:{
getVal(msg){
//msg就是,子组件传递的数据
}
}
< template>
< div>
父 {{msgVal}} 组件
< Header @childInput = ' getVal' > </ Header>
</ div>
</ template>
< script type = " text/javascript" >
import Header from './Header'
export default {
data ( ) {
return {
msgVal : ''
}
} ,
components : {
Header
} ,
methods : {
getVal ( msg ) {
this . msgVal = msg;
}
}
}
</ script>
< template>
< div>
子组件
< input type = " " name = " " v-model = ' changeVal' >
</ div>
</ template>
< script type = " text/javascript" >
export default {
data ( ) {
return {
changeVal : ''
}
} ,
watch : {
changeVal ( ) {
this . $emit ( "childInput" , this . changeVal) ;
}
}
}
</ script>
3.兄弟组件之间的传值
通过一个中转(bus)
A兄弟传值:
import bus from '@/common/bus'
bus.$emit("toFooter",this.msg);
B兄弟接收:
import bus from '@/common/bus'
bus.$on('toFooter',(data)=>{
//data是this.msg数据
})
< template>
< div>
< Header> </ Header>
< Footer> </ Footer>
</ div>
</ template>
< script type = " text/javascript" >
import Header from './Header'
import Footer from './Footer'
export default {
components : {
Header,
Footer
}
}
</ script>
< template>
< div>
header
< button @click = ' goFooter' > 传过去了</ button>
</ div>
</ template>
< script type = " text/javascript" >
import bus from '@/common/bus'
export default {
data ( ) {
return {
msg : "这是兄弟数据"
}
} ,
methods : {
goFooter ( ) {
bus. $emit ( "toFooter" , this . msg) ;
}
}
}
</ script>
< template>
< div>
footer
{{str}}
</ div>
</ template>
< script type = " text/javascript" >
import bus from '@/common/bus'
export default {
data ( ) {
return {
str : ''
}
} ,
mounted ( ) {
bus. $on ( 'toFooter' , ( data ) => {
this . str= data;
} )
}
}
</ script>