2017-04-27 93 views
9

我有一個動態的觀點:傳遞道具動態動態組件在VueJS

<div id="myview"> 
    <div :is="currentComponent"></div> 
</div> 

與相關Vue的實例:

new Vue ({ 
    data: function() { 
    return { 
     currentComponent: 'myComponent', 
    } 
    }, 
}).$mount('#myview'); 

這使我能夠動態地改變我的組件。

在我的情況下,我有三個不同的組件:myComponent,myComponent1myComponent2。我喜歡這樣它們之間進行切換:現在

Vue.component('myComponent', { 
    template: "<button @click=\"$parent.currentComponent = 'myComponent1'\"></button>" 
} 

,我想道具傳遞給myComponent1

當我將組件類型更改爲myComponent1時,如何傳遞這些道具?

+0

您經由元件'PROPNAME = 「propValue」'上屬性傳遞道具。這是你的問題嗎? – thanksd

+0

我不能因爲我從不寫''myComponent1 propName =「propValue」>'我用'$ parent.currentComponent = componentName'以編程方式更改組件 – Epitouille

+0

是的,但是你寫'

'。這就是你添加屬性的地方。 – thanksd

回答

25

動態傳遞的道具,你可以在v-bind指令添加到您的動態組件,並通過包含您的道具名稱和值的對象:

所以,你的活力的組成部分是這樣的:

<component :is="currentComponent" v-bind="currentProperties"></component> 

所以,現在

data: function() { 
    return { 
    currentComponent: 'myComponent', 
    } 
}, 
computed: { 
    currentProperties: function() { 
    if (this.currentComponent === 'myComponent') { 
     return { foo: 'bar' } 
    } 
    } 
} 

,當01:而在你的Vue的情況下,currentProperties可以改變基於當前組件是myComponent,它的foo屬性等於'bar'。如果不是,則不會傳遞屬性。

+0

看起來很完美,謝謝! – Epitouille

+0

爲什麼這不適合我? 它適用於第一個組件,但在更改「currentComponent」之後,我在子組件上未定義「e.currentProperties」。 –

+0

@RicardoVigatti,沒有看到你的任何代碼,很難知道 – thanksd

0

如果導入你的代碼通過需要

var patientDetailsEdit = require('../patient-profile/patient-profile-personal-details-edit')
和initalize數據實例如下

data: function() { 
 
      return { 
 
       currentView: patientDetailsEdit, 
 
      }

您也可以通過引用該組件name屬性,如果你的組件已經將其賦值

currentProperties: function() { 
 
       if (this.currentView.name === 'Personal-Details-Edit') { 
 
        return { mode: 'create' } 
 
       } 
 
      }