There is an array like the one below in merhava vue js, and when I send deletefuction(2) of it, I want to learn the index order of the data that is actually id
2, but I can't find it, where am I doing the search wrong?
{
id:1,
name:'hello',
},
{
id:2,
name:'about',
},
{
id:3,
name:'contact',
}
const state = reactive({
postList: [],
});
function deleteFuncton(idx) {
const found = state.postList.find(element => element.id === idx)
console.log(found)
}
CodePudding user response:
You can use filter to delete element from array, or if you just want to find index use findIndex:
const { reactive } = Vue
const app = Vue.createApp({
data() {
const state = reactive({
postList: [{id:1, name:'hello'}, {id:2, name:'about'}, {id:3, name:'contact'}]
})
function deleteFuncton(idx) {
//const found = state.postList.findIndex(p => p.id === idx)
//console.log(found)
state.postList = state.postList.filter(p => p.id !== idx)
}
return {
state, deleteFuncton
}
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div v-for="item in state.postList">
{{ item }}
<button @click="deleteFuncton(item.id)">del </button>
</div>
</div>