2017-03-15 87 views
1

我有一個Vue組件,我使用internalValue來訪問value屬性。我如何擴展這個也得到ID在組件中擴展Vue函數以顯示ID

即internalValue = value, id

我都試過,但我不知道如何添加這個功能internalValue裏面。我甚至試圖通過將所有值的實例更改爲id來獲取ID,但它仍然吐出值。

我很樂意讓他們成爲一個即value, id或訪問他們像data.valuedata.id

初始化Vue公司

new Vue({ 
     el: '#topic', 
     data: { 
     selectedTopic: null 
    } 
}); 

使用組件

<div class="form-group" id="topic"> 
    <topic v-model="selectedTopic"></topic> 
</div> 

註冊組件

Vue.component('topic', require('./components/Topicselect.vue')); 

組件

<template> 
    <div> 
    <label v-for="topic in topics" class="radio-inline radio-thumbnail"> 
     <input type="radio" v-model="internalValue" name="topics_radio" :id="topic.id" :value="topic.name"> 
     <span class="white-color lg-text font-regular text-center text-capitalize">{{ topic.name }}</span> 
    </label> 
    <ul class="hidden"> 
     <li>{{ internalValue }}</li> 
    </ul> 
    </div> 
</template> 

<script> 
export default { 
    props: ['value'], 
    data() { 
    return { 
     internalValue: this.value, 
     topics: [] 
    } 
    }, 
    mounted(){ 
    axios.get('/vuetopics').then(response => this.topics = response.data); 
    }, 
    watch: { 
    internalValue(v){ 
     this.$emit('input', v); 
     console.log('Topicselect: the value is ' + this.internalValue); 
    } 
    } 
} 
</script> 

回答

1

使用選定的主題爲你的價值。基本上,完全消除internalValue,只要點擊任何給定的單選按鈕就會發出與之相關的主題。這將滿足v-model,因爲它會監聽input事件(除非您自定義它)。

export default { 
    props: ['value'], 
    data() { 
    return { 
     topics: [] 
    } 
    }, 
    methods:{ 
    selectValue(topic){ 
     this.$emit('input', topic) 
    } 
    }, 
    mounted(){ 
    axios.get('/vuetopics').then(response => this.topics = response.data); 
    } 
}) 

而且你的模板

<template> 
    <div> 
    <label v-for="topic in topics" class="radio-inline radio-thumbnail"> 
     <input type="radio" @click="selectValue(topic)" name="topics_radio" :id="topic.id" :value="topic.name" :checked="value && topic.id == value.id"> 
     <span class="white-color lg-text font-regular text-center text-capitalize">{{ topic.name }}</span> 
    </label> 
    <ul class="hidden"> 
     <li>{{ value }}</li> 
    </ul> 
    </div> 
</template> 

這將設置你的Vue selectedTopic一個主題,這是一樣的東西

{ 
    id: 2, 
    name: "some topic" 
} 

根據您如何在模板中使用它。

Working example

+0

謝謝你,這是魔術在那裏:) –

+0

@ClintonGreen不客氣:)我在改變後的模板編輯,特別是':檢查=「值&& topic.id == value.id」'在某些時候你開始使用一個值而不是null。 – Bert

+0

呀一日2次,我得到了ID =零錯誤,但我看到的編輯。感謝堆。 –