2017-03-09 41 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