2017-03-15 88 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 =零错误,但我看到的编辑。感谢堆。 –