前端框架Vue(2)——vue 子父組件的傳參通訊

  父子間的通訊傳值是 vue 中的一個重要的內容和掌握點。vue

  *vue2.0 推薦使用 vuex,全局進行狀態管理。(後面再講)git

  首先講一下遇到的 需求背景:github

這裏寫圖片描述

解釋一下:
  組件之間的關係:web

<div id="app">
    <loginPage v-on:showState="changeState" v-if="loginShow" :fromParent="fromParent"></loginPage>
    <div class="web-content" v-if="webShow">
      <phHeader :headerUserName="headerUserName"></phHeader>
      <div>
        <router-view></router-view>
      </div>
      <phFooter></phFooter>
    </div>    
  </div>

這裏寫圖片描述

一、子組件 login 傳參數給父組件 app.vue

$emit

用法:vm.$emit( event, […args] ),觸發當前實例上的事件。vuex

子組件中代碼app

submitForm:function(formName){
    //與父組件通訊傳值
    this.$emit('showState', [this.loginShow,this.formName.user])
}

submitForm 是一個點擊事件, showState 是一個方法,後邊是多個參數寫法。this

父組件中代碼spa

首先須要在 子組件中綁定 showState 事件,前一個 showState 是在子組件定義的,後面的 changeState 是新定義的方法。code

<loginPage v-on:showState="changeState" v-if="loginShow" :fromParent="fromParent"></loginPage>
changeState:function(data){
      //console.log(data)
      if(data[0] === false){
        console.log('執行')
        this.webShow = true;//顯示web應用內容
        this.loginShow = false;//隱藏login組件
        this.headerUserName = data[1];//賦值headerUserName
      }
    }

而後就能在方法中得到子組件傳來的參數:
data:[false, "allen"]0: false1: "allen"length: 2__proto__: Array(0)component

二、父組件 app.vue 傳參數給子組件 ph-Header

props

父組件中代碼:

引入在父組件中的 ph-Header 子組件須要綁定 headerUserName,前一個 headerUserName 是子組件中定義的。後一個纔是父組件中的參數。

<phHeader :headerUserName="headerUserName"></phHeader>
export default {
  name: 'app',
  data () {
    return {
      loginShow: true,
      webShow: false,
      fromParent:'——來自父組件',
      headerUserName: '用戶名'
    }
  },
  components:{
    phHeader,
    phFooter,
    loginPage
  },
  methods:{
    changeState:function(data){
      console.log(data)
      if(data[0] === false){
        console.log('執行')
        this.webShow = true;//顯示web應用內容
        this.loginShow = false;//隱藏login組件
        this.headerUserName = data[1];//賦值headerUserName
      }
    }
  }
}

子組件中代碼

子組件中須要接收 headerUserName

export default {
        name: '',
        data () {
            return {

            }
        },
        props:[
            'headerUserName'
        ]
    }

關於父子組件的傳參通訊,有須要的話這邊有一個比較完整的項目放在個人github上:https://github.com/AllenChine...

但願對那麼可愛,還來看我博客的你 有些許的幫助!

相關文章
相關標籤/搜索