vue--三種組件中之間的傳值


一、父子組件之間的傳值----props/$emit

組件之間的傳值,我們比較常用到的是props/$emit

1、父組件向子組件傳值--props

這里我們在父組件中定義的extensionObj是一個對象

<Extension :extensionObj="extensionObj"/>
data(){
    return{
        extensionObj: {},
    }
}

在子組件中接收值

props:['extensionObj'],

或者

props:{
    extensionObj: {
        type: Object,
        default: {}
    },
},

2、子組件想父組件傳值

子組件:

<col @click="tableClickBtn(item)"></col>

寫個方法觸發

tableBtnClick(item){
    this.$emit('select',item);
}

父組件:

<StaffDialog ref="staffDialogRef" @select="staffDialogSelect"/>

寫個方法接收

staffDialogSelect(item) {
    this.searchObj = item;
}

這里組件的注冊就不寫了

二、父組件向下(深層)子組件傳值----provide/inject

這里引用vue官網文檔里的話

  • 類型:

    • provide:Object | () => Object
    • inject:Array<string> | { [key: string]: string | Symbol | Object }
  • 詳細:

    provide 和 inject 主要在開發高階插件/組件庫時使用。並不推薦用於普通應用程序代碼中。

  • provide 選項應該是一個對象或返回一個對象的函數
  • inject 選項應該是:

    • 一個字符串數組,或
    • 一個對象,對象的 key 是本地的綁定名,value 是:
      • 在可用的注入內容中搜索用的 key (字符串或 Symbol),或
      • 一個對象,該對象的:
        • from property 是在可用的注入內容中搜索用的 key (字符串或 Symbol)
        • default property 是降級情況下使用的 value

  示例

// 父級組件提供 'foo'
var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

// 子組件注入 'foo'
var Child = {
  inject: ['foo'],
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}

記錄一段實戰中的代碼

父組件中getCustInfo為接口返回的數據
provide(){
    return {
        getCustInfo: this.getCustInfo
    }
},

子組件接收

inject: ['getCustInfo'],

這里的getCustInfo也可以個是一個方法,返回一個函數

methods:{
    getCustInfo(){
        return this.custInfo; //custInfo是接口返回的數據
    }
}

那么,子組件的接收應該這樣

custInfo(){
    return this.getCustInfo();
},

 

三、訪問父、子組件----ref、$parent/$child

1、ref--在父組件中訪問子組件

引用官網api:

盡管存在 prop 和事件,有的時候你仍可能需要在 JavaScript 里直接訪問一個子組件。為了達到這個目的,你可以通過 ref 這個 attribute 為子組件賦予一個 ID 引用。例如:

<base-input ref="usernameInput"></base-input>

現在在你已經定義了這個 ref 的組件里,你可以使用:

this.$refs.usernameInput

注意:$refs 只會在組件渲染完成之后生效,並且它們不是響應式的。這僅作為一個用於直接操作子組件的“逃生艙”——你應該避免在模板或計算屬性中訪問 $refs

2、父、子組件之間的訪問

引用官網api:

指定已創建的實例之父實例,在兩者之間建立父子關系。子實例可以用 this.$parent 訪問父實例,子實例被推入父實例的 $children 數組中。

節制地使用 $parent 和 $children - 它們的主要目的是作為訪問組件的應急方法。更推薦用 props 和 events 實現父子組件通信

 

這里組件之間的訪問,目前實戰中用到的較少。按官網的話,就是不太建議使用。

至於event bus暫時還沒有用到過,Vuex狀態管理用於權限管理,這個就后期再寫寫

 


免責聲明!

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



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