2017-03-09 45 views
3
從組件數據

我有以下組成部分:如何獲得VueJS

組件

<template> 
<div> 
    <label class="typo__label">Single selecter</label> 
    <multiselect v-model="value" :options="options" :searchable="false" :close-on-select="false" :show-labels="false" placeholder="Pick a value"></multiselect> 
</div> 
</template> 

<script> 
import Multiselect from 'vue-multiselect' 

export default { 
    components: { 
    Multiselect 
    }, 
    data() { 
    return { 
     value: '', 
     options: ['Select option', 'options', 'selected', 'mulitple', 'label', 'searchable', 'clearOnSelect', 'hideSelected', 'maxHeight', 'allowEmpty', 'showLabels', 'onChange', 'touched'] 
    } 
    } 
} 
</script> 

我使用它在我的網頁像這樣:

<p id="app-two"> 
    <dropdown></dropdown> 
    @{{ value }} 
    @{{ message }} 
</p> 

<script> 
    new Vue({ 
    el: '#app', 
    data: { 
     message: 'Test message' 
    } 
}); 
</script> 

當我運行該頁面,@ {{message}}顯示「測試消息」,但@ {{value}}爲空。 我可以在VueJS Dev Tools中看到更新下拉組件的值,但它不會顯示在頁面上。我如何訪問我的vue元素中的組件數據?像@ {{dropdown.value}}

回答

3
<template> 
    <div> 
     <label class="typo__label">Single selecter</label> 
     <multiselect v-model="internalValue" :options="options" :searchable="false" :close-on-select="false" :show-labels="false" placeholder="Pick a value"> </multiselect> 
    </div> 
</template> 

<script> 
    import Multiselect from 'vue-multiselect' 

    export default { 
     components: { 
     Multiselect 
     }, 
     props: ['value'], 
     data() { 
     return { 
      internalValue: this.value, 
      options: ['Select option', 'options', 'selected', 'mulitple', 'label', 'searchable', 'clearOnSelect', 'hideSelected', 'maxHeight', 'allowEmpty', 'showLabels', 'onChange', 'touched'] 
     } 
     }, 
     watch:{ 
     internalValue(v){ 
      this.$emit('input', v); 
     } 
     } 
    } 
</script> 

,並在頁面

<p id="app-two"> 
    <dropdown v-model="selectedValue"></dropdown> 
    @{{ selectedValue}} 
    @{{ message }} 
</p> 

<script> 
    new Vue({ 
    el: '#app', 
    data: { 
     selectedValue: null 
     message: 'Test message' 
    } 
}); 
</script> 

Here is an example,不使用多選,但實現了v-model支持的自定義組件。

+0

嗨,沒有得到組件的數據。我想我需要使用道具,但我無法弄清楚它在這裏的工作原理。謝謝 –

+0

@ClintonGreen我誤解了你的代碼。它看起來像是在你自己的自定義組件中包裝多選?在這種情況下,您可能希望在組件中實現v模型支持,或者,您可以只發出該值。 – Bert

+0

@ClintonGreen更新了示例以實現自定義組件的v模型。 – Bert