1.父组件传子组件
2.子组件传父组件
3.兄弟组件之间传值
1.父组件传子组件(prop)
父组件中的 msg传到子组件中去
<template>
<div>
<h1>关于我们</h1>
<div class="container">
<h3 class="title">Hello 关于我们</h3>
<card :msg="msg" />
</div>
</div>
</template>
<script>
import Card from "./Card.vue";
export default {
components: { Card },
data() {
return {
msg: "没想到把我过来了",
};
},
};
</script>
子组件使用props['msg']接
<template>
<div class="card">
<div class="title">哈哈</div>
<div class="list">
<div class="item">{{msg}}</div>
<div class="item">vue build</div>
</div>
</div>
</template>
<script>
export default {
props:["msg"]
}
</script>
2.子组件传父组件(?this.$emit("事件名称","传入的值"))
子组件:this.$emit("change",this.chuanchu)
<template>
<div class="card">
<button @click="btn">输出</button>
<div class="title">哈哈</div>
<div class="list">
<div class="item">{{msg}}</div>
<div class="item">vue build</div>
</div>
</div>
</template>
<script>
export default {
props:["msg"],
data() {
return {
chuanchu:"子组件即将进入父组件的值"
}
},
methods:{
btn(){
// this.$emit("事件名称","传入的值")
this.$emit("change",this.chuanchu)
}
}
}
</script>
父组件:@change="changeBtn"? ?changeBtn(d){}
<template>
<div>
<h1>关于我们</h1>
<div class="container">
<h3 class="title">Hello 关于我们</h3>
<!-- 自定义事件change -->
<card :msg="msg" @change="changeBtn" />
</div>
</div>
</template>
<script>
import Card from "./Card.vue";
export default {
components: { Card },
data() {
return {
msg: "没想到把我过来了",
};
},
methods:{
changeBtn(d){
console.log(d)
}
}
};
</script>
3.兄弟组件之间传值
1.弄一个公共的bus.js文件(实例化vue)
组件A代码:
<template>
<div>
AAAAAAA
<button @click="btn">走起</button>
</div>
</template>
<script>
import bus from './bus'
export default {
data() {
return {
aStr:"A中的数据"
}
},
methods:{
btn(){
bus.$emit("change",this.aStr)
}
}
}
</script>
组件B的代码块:
<template>
<div>
BBBBBB{{bstr}}
</div>
</template>
<script>
import bus from './bus'
export default {
data() {
return {
}
},
computed:{
bstr(){
bus.$on("change",function(d){
console.log(d);
})
}
}
}
</script>
|