Reputation: 3108
i want to remove elements from this array when they get selected but v-on:change is not the right option because when you select an item, the select value will change twice so the method will also get executed twice (two elements will be removed) i thought of making a new directive to do this job ,but i want to leave it as my last option ...thank you
new Vue({
el:"#app",
data :{
arr:['1','2','3','4'],
selected:""
},
methods :{
splice (){
this.arr.splice(this.arr.indexOf(this.selected),1)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select v-model="selected" @change="splice">
<option v-for="item in arr" >{{ item }}</option>
</select>
<div>
this was my attempt, but like i said it get executed twice because select value changes twice and also i want to do more stuff on item selection so maybe i should just make a directive
Upvotes: 0
Views: 2931
Reputation: 1
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>
Upvotes: 2
Reputation: 214927
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>
Upvotes: 2
Reputation: 18187
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>
Upvotes: 2