vue 组件之间相互传值 父传子 子传父

1、父传子 把要传入的值放到父标签里  子组件使用props接收 

父写法

子写法

2、子传父

 子组件:

childrenOnclick() {
  // 发布自定义事件
  this.$emit("back", "我来了")//第一个参数是父组件中v-on绑定的自定义回调方法,第二个参数为传递的参数
}
父组件
<children-item  v-on:back="handleParentClick"></children-item>

3、组件之间的通信

   简单的通信使用vue实例解决,复杂的大型项目使用vuex状态管理。

    1、新建一个vue实例来进行传递消息

   var vm = new Vue();

2、组件一发送消息
  sendMsg: function () { //传参方法
console.log(555);
vm.$emit("eventBus","我是组件一");//定义方法名和要传输的数据
}


3、组件二接收消息
  receive:function () {
vm.$on("eventBus",function (val) { //接收组件二的参数
console.log(val) //我是组件一
})
}

    

 完整代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.js"></script>
</head>
<body>
<div id="app">
<child-component :message="msg" v-on:allback="updatea"></child-component>
<child-component2></child-component2>
</div>
<script>
    var vm = new Vue();

    //组件一  发送信息给父组件 、 接收组件二消息
    Vue.component('childComponent',{
        props:['message'],
        template: `<div @click="sendMsg">{{ message }}</div>`,
        data() {
            return{
                son:"我是你儿子"
            }
        },
        mounted(){
            this.receive()
        },

        methods:{
            sendMsg: function () { //传参方法
                console.log(555);
                this.$emit('allback', this.son); //第一个参数是父组件中v-on绑定的自定义回调方法,第二个参数为传递的参数
            },
            receive:function () {
                vm.$on("eventBus",function (val) {  //接收组件二的参数
                    console.log(val)
                })
            }
        }
    });
    //组件二 发送信息给组件一
    Vue.component('childComponent2',{
        props:['message'],
        template: `<div @click="sendMsg">告诉大哥</div>`,
        data() {  //为什么不能写成data:{} 报错
            return{
                twoson:"我是你弟弟"
            }
        },
        methods:{
            sendMsg: function () { //传参方法
                console.log(555);
               vm.$emit("eventBus",this.twoson);//定义方法名和要传输的数据
            }
        }
    });
    new Vue({
        el:'#app',
        data:{
            msg:"我是你爸爸"
        },
        methods:{
            updatea:function (msg) {
                console.log(6666)
                this.msg=msg
            }
        }
    })
</script>
</body>
</html>

  



原文地址:https://www.cnblogs.com/yangqing22/p/10276335.html