1. 组件传值之父传子
父子之间的传值比较简单,父传子直接通过props来进行传值,在子组件中要定义对应的prop来获取父组件的值。
代码:
<childredone
@changeparent="changemsgg"
:handler="num"
:strings = "msg"
>
</childredone>
props:{
handler:Number,
strings:String
},
2.组件传值之子传父(事件定义,$parent
,反向porps,vuex)
子传父,借助事件定义:$emit
方法,子组件定义自定义事件,利用$emit
触发事件,来执行父组件的函数,来达到子传父效果。
代码示例:
<template id="parent">
<div>
<h2>父元素</h2>
<h3>{{msg}}</h3>
<button @click="chuanzi">父传子</button>
<hr>
<childredone
@changeparent="changemsgg"
:handler="num"
>
</childredone>
<hr>
<childredtwo>
</childredtwo>
</div>
</template>
<template id="childredone">
<div>
<h2>子元素一</h2>
<h2>{{handler}}</h2>
<h2>{{strings}}</h2>
<h3>{{texts}}</h3>
<button @click="changeMsg">点击切换父元素的内容</button>
</div>
</template>
methods: {
changeMsg() {
this.$emit("changeparent", this.masg)
},
},
子组件点击事件触发,执行changeMsg函数,在子组件上定义了自定义事件:changeparent,点击的会后使用$emit
方法,触发该事件,执行父组件里面的changemsgg方法,打到修改父组件的值和传递参数的效果。
3.组件传值之兄弟之间传值
兄弟之间传值可以利用bus总线来传递。
代码示例:
<template id="childredone">
<div>
<h2>子元素一</h2>
<h2>{{handler}}</h2>
<h2>{{strings}}</h2>
<h3>{{texts}}</h3>
<button @click="changeMsg">点击切换父元素的内容</button>
</div>
</template>
<template id="childredtwo">
<div>
<h2>子元素二</h2>
<button @click="changebrother">点击切换兄弟的内容</button>
</div>
</template>
<script>
const bus = new Vue();
Vue.component("childredone", {
template: "#childredone",
data() {
return {
masg: "子元素修改后的值",
texts: "兄弟元素的值"
}
},
props:{
handler:Number,
strings:String
},
methods: {
changeMsg() {
this.$emit("changeparent", this.masg)
},
},
mounted(){
bus.$on("changetexts", msg => { // 必须使用箭头函数 保留this 指向
console.log(msg);
this.texts = msg;
})
}
})
Vue.component("childredtwo", {
template: "#childredtwo",
data() {
return {
textss: "兄弟间传值"
}
},
methods: {
changebrother() {
bus.$emit("changetexts", this.textss)
}
}
})
</script>
兄弟间传值,在一个兄弟中定义事件,在另外一个兄弟中利用on监听该事件,来达到兄弟间传值的效果