Vue.js如何删除组件v-for值

时间:2017-05-04 23:44:35

标签: javascript vue.js

我正在学习Vue,所以我创建了单选按钮组件,但我正在努力如何删除这些值。我当前的解决方案删除了​​实际值,但仍然显示选择。

这是组件

<template id="fradio">
<div>

<div class="field is-horizontal">
  <div class="field-label" v-bind:class = "{ 'required' : required }">
    <label
        class = "label"
        >{{label}}
    </label>
  </div>
  <div class="field-body">

  <div>
    <div class="field is-narrow">
      <p class="control" v-for="val in values">
        <label class = "radio">
          <input 
            type="radio"            
            v-bind:name = "name"
            v-bind:id = "name"
            @click = "updateValue(val)"
          >
          <span>{{val[valueLabel]}}</span>
          <span v-if="!valueLabel">{{val}}</span>
        </label>
        <label class="radio">
          <button class="delete is-small" @click="removeValue"></button>
        </label>  

        <slot></slot>
      </p>      
    </div>
   </div>


</div>
</template>

<script>
    export default {
        props: {

            label: {
              type: String,
              required: true,
            },

            inputclass: {
                type: String,
            },
            required: {
                type: Boolean,
                default: false,
            },
            valueLabel:{
                type: String,
            },
            returnValue:{
                type: String,

            },
            values:{},
            name:'',
        },
        data() {
            return {

            };
        },


methods: {

    updateValue: function (value) {
        var selectedValue;
        (!this.returnValue) ? selectedValue = value : selectedValue = value[this.returnValue];

      this.$emit('input', selectedValue)    
    },

  removeValue: function() {
    this.$emit('input',null);
  },

},

}

</script>

应该很容易,但我需要有人指出明显的......

1 个答案:

答案 0 :(得分:1)

<强>更新

我刚刚意识到您可能更专注于不动态更新的数据,这意味着您的问题可能是父组件中的数据未被更新。你的大部分数据都是作为道具传递下来的,所以我需要看看在父组件中如何触发事件以帮助诊断出错了什么。根据您提供的代码,看起来您的removeValue()函数正在发出事件,但我看不到任何实际删除该值的代码。

我会检查父组件以确保它正在删除子组件,这应该可以解决您的问题!

初步答案:

通常,从v-for列表中删除项目时,您需要知道项目的索引并使用Array.splice来修改列表以将其删除。

这是我头脑中的一个通用示例。

<template>
    <ul>
        <li v-for="(fruit, index) in fruits"      
            @click="removeItem(index)">
            {{ fruit }}
        </li>
    </ul>
</template>

<script>
    export default {
        data() {
            return {
                fruits: ['Apple', 'Banana', 'Clementines']
            }
        },
        methods: {
            removeItem(index) {
                this.fruits.splice(index, 1)
            }
        }
    }
</script>

如果您有任何疑问,请与我联系!