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>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM