[Vuejs]-Vue.js โ€“ How to remove an array element upon selection by <select> tag

2๐Ÿ‘

โœ…

If you have a default option with a null value to fallback to, it will work by first re-assigning this.selected = null and then splicing the options array:

new Vue({
  el: "#app",
  data() {
    return {
      arr: ['1', '2', '3', '4'],
      selected: null
    }
  },
  methods: {
    removeElement(e) {
      this.selected = null
      this.arr.splice(this.arr.indexOf(e.target.value), 1)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <select v-model="selected" @change="removeElement">
    <option :value="null" disabled>-- Select --</option>
    <option v-for="item in arr">{{ item }}</option>
  </select>
</div>
๐Ÿ‘คBrian Lee

2๐Ÿ‘

Here is an option using a simple list to achieve what you needed, which seems to be a better fit for your case;

new Vue({
  el: "#app",
  data: {
    arr: ['1','2','3','4'],
    removed: ""
  },
  methods: {
    splice (item, index) {
      this.removed = item
      this.arr.splice(index, 1)
    }
  }
})
ul {
  border: 1px solid black;
  overflow-y: scroll;
  height: 55px;
  width: 50px;
  padding: 0px;
}

li {
  list-style-type: none;
}    
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <ul>
    <li v-for="(item, index) in arr" @click="splice(item, index)">{{ item }}</li>
  </ul>
  Removed: {{ this.removed }}
</div>
๐Ÿ‘คPsidom

2๐Ÿ‘

Another solution is using watch property to watch the selected item and remove it from the array:

new Vue({
  el: "#app",
  data: {
    arr: ['1', '2', '3', '4'],
    selected: ""
  },
  methods: {

  },
  watch: {
    selected(v) {
      if (this.selected !== "") {
        this.arr.splice(this.arr.indexOf(v), 1)
      }
      this.selected=""
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select v-model="selected">
    <option v-for="item in arr">{{ item }}</option>
  </select>
  <div>

Leave a comment