vue组件间通讯,相互传递数据

一、父组件向子组件传递数据(利用子组件的props属性)

<div id="app">
  <parent-component></component> 
  
  <template id="parent-component">
    <h2>{{title}}-->{{msg}}</h2>
    <child-component :md="msg"></child-component>
  </template>
  
  <template id="child-component">
    <h2>{{title}}-->{{msg}}<h2>
    <input type="button" value="获取父组件数据">
  </template>
</
div>
var vm=new Vue({
    el:"#app",
    data:{},
    methods:{},
    components:{
      "parent-component":{
        data(){
          return {
            title:"我是父组件",
            msg:"我是父组件数据"
          }
        },
        template:"#parent-component",
        components:{
          "child-component":{
            data(){
              return {
                title:"我是子组件",
                msg:"我是子组件数据"
              }
            },
            methods:{
              change(){
                this.msg=this.md; //此时将子组件属性md(md的属性值来自于父组件:msg)赋给子组件msg
              }
            },
            props:[md],
            template:"#child-component"
          }
        }
      }
    }
  });
 

二、子组件向父组件传递数据

1.利用this.$emit('事件名称',数据)向父组件广播数据

2.v-on监听接收数据

1 <div id="app">
  <parent-component></parent-component>

  <template id="parent-component">
    <h3>{{title}}--->{{msg}}</h3>
    <child-component @child-msg="get"></child-component>
  </template>
  <template id="child-component">
    <h3>{{title}}--->{{msg}}</h3>
    <input type="button" value="发送数据到父组件" @click="send">
  </template>

 </
div>
1 var vm=new Vue({
2   el:"#app",
   data:{},
   methods:{},
   components:{
     "parent-component":{
        data(){
          return {
            title:"我是父组件",
            msg:"我是父组件数据"
          }
        },
        methods:{
          get(msg){
            this.msg=msg //接收子组件传递过来的数据
          }
        },
        template:"#parent-component",
        components:{
          "child-component":{
            data(){
              return {
                title:"我是子组件",
                msg:"我是子组件数据"
              }
            },
            methods:{
              send(){
                this.$emit("child-msg",this.msg);//将子组件的数据发射(广播)出去
              }
            },
            template:"#child-component"
          }
        }
      }
   }
3 })

猜你喜欢

转载自www.cnblogs.com/junechen/p/9300102.html