Vue组件传值(父传子,子传父,兄弟相传)

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监听该事件,来达到兄弟间传值的效果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值