【问题标题】:Extend Vue function in component to display ID在组件中扩展 Vue 功能以显示 ID
【发布时间】:2017-03-15 21:11:02
【问题描述】:

我有一个 Vue 组件,我正在使用 internalValue 来访问 value 属性。我将如何扩展它以获得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>

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案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.

    【讨论】:

    • @ClintonGreen 不客气 :) 我稍后在对模板的更改中进行了编辑,特别是 :checked="value &amp;&amp; topic.id == value.id",以防在某些时候您以值而不是 null 开始。
    • 是的,前两次我得到了 id = null 错误,但我看到了编辑。谢谢大家。
    猜你喜欢
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2021-12-13
    • 2021-11-26
    • 2014-09-20
    • 2020-01-09
    • 1970-01-01
    相关资源
    最近更新 更多