首页 > 代码库 > vue子组件向父组件传值

vue子组件向父组件传值

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子组件向父组件传值