码迷,mamicode.com
首页 > 其他好文 > 详细

Vue2父子组件间的通信

时间:2017-08-09 15:34:28      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:return   自定义事件   text   接受   image   radius   tom   cli   info   

技术分享

父组件通过 props 向下传递数据给子组件,子组件通过 events 向上给父组件发送消息。


父组件:
<div>
    <div style="background:#34495E;color: #fff; padding:20px">
      <p style="margin-bottom: 20px">这是父组件</p>
      <div style="background:#E74C3C;color: #fff; padding:20px; margin-top:20px">
        <p>接受来自子组件的内容: </p>
        <p style="margin-top:20px;background:#fff; color:#000; padding:5px; line-height:1.5;">{{hello}}</p>
      </div>
    </div>
    <div style="background:#34495E;color: #fff; padding:20px; margin-top:20px">
      <p style="margin-bottom: 20px">这是子组件</p>
      <musicsearch @trans="transContent" :pupu="hello" :info="info"></musicsearch>
    </div>
  </div>
export default {
  components: {
    musicsearch
  },
  data() {
    return {
      hello: ‘‘,
      info: ‘‘
    }
  },
  methods: {
    transContent(msgs) {
      this.hello = msgs;
      this.info = msgs;
    }
  }
}

  

子组件:
<div>
    <div style="margin-top:20px; background:#E74C3C; padding:10px;">
      <input type="text" ref="ipt" style="border:none; margin-top:10px; margin-bottom: 20px; border-radius:4px; width:90%; height:18px; padding:5px; line-height:18px; border:1px solid #fff">
      <button @click="sendVal()" style="margin-bottom: 20px; border:none; outline:none; border-radius:4px; height:28px; line-height:28px; background:#F1C40F; color:#fff;">向父组件发送内容按钮</button>
    </div>
    <div style="margin-top:20px; background:#E74C3C; padding:10px;">
      <button @click="click()" style=" margin-top:10px; border:none; outline:none; border-radius:4px; height:28px; line-height:28px; background:#F1C40F; color:#fff;">接受来自父组件的内容按钮</button>
      <div style="margin-top:20px;background:#fff; color:#000; padding:5px; line-height:1.5;">{{msg}}</div>
    </div>
  </div>

export default {
  name: ‘girl-group‘,
  props: {
    info: ‘‘
  },
  data() {
    return {
      msg: ‘‘
    }
  },
  methods: {
    sendVal() {
      this.$emit(‘trans‘, this.$refs.ipt.value);
    //这里在父组件使用v-on来监听子组件上的自定义事件($emit的变化),一旦发生变化click方法里的值就会跟着改变,调用click事件可看到信息
    },
    click() {
      this.msg = this.info;
    }
  }
}

  

  

 

  

 

  

Vue2父子组件间的通信

标签:return   自定义事件   text   接受   image   radius   tom   cli   info   

原文地址:http://www.cnblogs.com/kymming/p/7325119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!