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

vue子组件向父组件传值

时间:2017-04-14 19:36:41      阅读:325      评论:0      收藏:0      [点我收藏+]

标签:toc   efault   log   2.0   内容   .sh   定义   mit   传递参数   

vue2.0中通过$emit事件在子组件中自定义事件,通过操作子组件中的事件,向父组件传递参数;

首先写一个叫做parentComp.vue的父组件:

<template>
  <div>
    <childComp01 :fromParentToChild="fromParentToChild" :isShow="show" @showParentComp="eventFromChild"></childComp01>
    <childComp02 @eventFromChild02="eventFromChild02" :fromParentToChild="fromParentToChild" :isShow="!show"></childComp02>
  </div>

</template>
<script>
  import childComp01 from ‘./childComp.vue‘
  import childComp02 from ‘./childComp02.vue‘
  export default{
    data(){
      return{
        show:false,//是否展示子组件内容
        fromParentToChild:""
      }
    },
    components:{childComp01,childComp02},
    methods:{
      showChild(){
        this.show = true
      },
      eventFromChild(dataIf){
        console.log(dataIf.show)
        this.show=dataIf.show
        this.fromParentToChild = dataIf.mes
      },
      eventFromChild02(dataIf){
        console.log(dataIf.show)
        this.show=dataIf.show
        this.fromParentToChild = dataIf.mes
      }
    }
  }
</script>

  

然后定义子组件childComp01和childComp02

<template>
  <div v-if="isShow">
    <div>子组件内容01:</div>
    {{fromParentToChild}}
    <div>
      <button @click="showParentComp">点击显示子组件02内容</button>
    </div>
  </div>
</template>
<script>
  export default{
    props:[‘fromParentToChild‘,‘isShow‘],
    data(){
      console.log(this.fromParentToChild)
      return{
        dataIf:{
          mes:"来自子组件01的内容",
          show:false
        }
      }
    },
    methods:{
      showParentComp(){
        this.$emit("showParentComp",this.dataIf)
      }
    }
  }
</script>

  

childComp02.vue

<template>
  <div class="childComp-02" v-if="isShow">
    {{fromParentToChild}}
    <div><button @click="toParentComp">这是子组件02</button></div>
  </div>
</template>
<script>
  export default{
    props:[‘isShow‘,‘fromParentToChild‘],
    data(){
      return{
        dataIf:{
          show:true,
          mes:"从子组件02传过来的信息"
        }
      }
    },
    methods:{
      toParentComp(){
        this.$emit("eventFromChild02",this.dataIf)
      }
    }
  }
</script>

  

 

vue子组件向父组件传值

标签:toc   efault   log   2.0   内容   .sh   定义   mit   传递参数   

原文地址:http://www.cnblogs.com/zhangxiaoshu/p/6710361.html

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