一.父传子props
父组件
子组件接收使用props
注意:props是只读的修改会报错
二.子传父---自定义事件
子组件
父组件
三.兄弟组件传值---EventBus
新建EventBus.js
import Vue from "vue";
export default new Vue()
left组件
四、整体代码
index页面
<template>
<div>
<header class="header">
<div>头部</div>
<div>子组件给父组件的值--{{sonVal}}</div>
</header>
<div style="display: flex">
<left :msg="msg" :val="val"></left>
<Right @send="getSonVal"></Right>
</div>
</div>
</template>
<script>
import Left from "../components/Left";
import Right from "../components/Right";
export default {
name: "index.vue",
components:{
Left,
Right
},
data(){
return{
msg:"父传子",
val:"1000",
sonVal:""
}
},
methods:{
getSonVal(val){
this.sonVal=val
console.log(val)
}
}
}
</script>
<style scoped>
.header{
background-color: #da871a;
width: 100%;
height: 100px;
color: #ffffff;
font-size: 30px;
}
</style>
Left组件
<template>
<div class="left">
<h1>left</h1>
<div>{{msg}}-----{{val}}------ <button @click="val=123">修改</button></div>
<div><button @click="sendRight">向兄弟组件传值</button></div>
</div>
</template>
<script>
import bus from "../utils/EventBus"
export default {
//只读修改会报错
props:['msg','val'],
name: "Left",
data(){
return{
msgLeft:"向兄弟组件传值"
}
},
methods:{
sendRight() {
bus.$emit('send',this.msgLeft)
}
}
}
</script>
<style scoped>
.left{
width: 50%;
height: 200px;
color: #ffffff;
font-size: 15px;
background-color: cadetblue;
}
</style>
Right组件
<template>
<div class="right">
<h1>Right</h1>
<div>子组件给父组件传值{{count}}-----<button @click="send">传值</button></div>
<div>{{msgFromLeft}}</div>
</div>
</template>
<script>
import bus from "../utils/EventBus"
export default {
name: "Right",
data(){
return{
count:0,
msgFromLeft:''
}
},
created() {
bus.$on('send',res=>{
this.msgFromLeft=res
})
},
methods:{
send(){
this.count+=1
this.$emit('send',this.count)
console.log(this.count)
}
}
}
</script>
<style scoped>
.right{
width: 50%;
height: 200px;
color: #ffffff;
font-size: 15px;
background-color: #cd7eec;
}
</style>
EventBus
import Vue from "vue";
export default new Vue()