2016-12-29 54 views
1

表(母公司)成分:家長的onChange設置子屬性爲true

export default { 
    template: ` 
    <form name="form" class="c form" v-on:change="onChange"> 
     <slot></slot> 
    </form>`, 
    methods: { 
    onChange:function(){ 
     console.log("something changed"); 
    } 
    } 
}; 

和C-工具欄組件(子)是(如果存在的話)的C形的凹槽內,

export default { 
    template: ` 
    <div class="c tool bar m006"> 
     <div v-if="changed"> 
     {{ changedHint }} 
     </div> 
     <!-- some other irrelevant stuff --> 
    </div>`, 
    props: { 
    changed: { 
     type: Boolean, 
     default: false, 
    }, 
    changedHint: String 
    } 
}; 

我想實現的是,那個時候的c-form的onChange被炒魷魚的功能 檢查,如果孩子的C-工具欄存在& &它有一個changedHint文本聲明(從後端)應該改變c-tool-bar的道具「更改」爲true,c-bar-tool自動更新,以便v-if="changed"實際顯示changedHint。我閱讀了vue.js文檔,但我不知道從哪裏開始,以及正確的方法是什麼。

回答

2

您可以使用兩個組件是這樣的:

<parent-component></parent-component> 

您將通過在T他:changed支持在data()的父組件中定義的變量。請注意0​​,我們使用的是dynamic props,所以一旦父值中的prop值被更改,它也會更新孩子。 要更改提示的顯示,請將支持的變量的值更改爲子組件:

export default { 
    template: ` 
    <form name="form" class="c form" v-on:change="onChange"> 
     <child-component :changed="shouldDisplayHint"></child-component> 
    </form>`, 
    data() { 
    return { 
     shouldDisplayHint: false, 
    }; 
    }, 
    methods: { 
    onChange:function(){ 
     this.shouldDisplayHint = true; // change the value accordingly 
     console.log("something changed"); 
    } 
    } 
}; 
+0

這也是個好主意。他可以選擇使用$ refs並傳遞單向綁定的道具 –

+0

我是否需要對子模板進行更改?我得到以下錯誤:[Vue警告]:屬性或方法「shouldDisplayHint」未在實例上定義,但在渲染過程中引用。確保在數據選項中聲明反應數據屬性。 (在組件中找到) – TITO

+0

您是否在父組件的data屬性中添加了'shouldDisplayHint'? – Nora

1

一個簡單的方法是使用$refs

當您將創建父組件內的子組件,你應該是這樣的:<c-tool-bar ref="child">,然後你可以在你的父組件代碼中使用它:

methods: { 
    onChange:function(){ 
     this.$refs.child.(do whatever you want) 
    } 
    } 

希望它可以幫助,但在任何情況下,更多的問題:https://vuejs.org/v2/guide/components.html#Child-Component-Refs

相關問題