有没有一种正确的方法可以在不重新加载所有数据的情况下从 vueJS 数组列表中刷新特定行?
在这种情况下,它是一个电话列表。
<template>
<table class="table">
<tr v-for="phone in phones">
<td @click="edit(phone.id)">
{{phone.number}}
</td>
<td class="pointerCursor" @click="edit(phone.id)">
{{phone.comment | truncate(90)}}
</td>
</tr>
</table>
</template>
<script>
export default {
data () {
return {
phones = [
{id:1, number: '001 656 88 44', comment:''},
{id:2, number: '610-910-3575 x2750', comment:'Quod odit quia'},
{id:3, number: '536.224.2639 x714', comment:'primary phone'},
{id:5, number: '0034 556 65 77', comment:'home phone phone'},
]
}
},
methods: {
edit(id) {
// update using an api that returns the updated data.
var updatedPhone = update(id)
// how to update with reloading all the phone list?
// ...
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
PS:这是一个代码,只是为了演示问题。
const currentIndex = this.phones.findIndex(p => p.id === id);
this.phones.splice(currentIndex, 1, updatedPhone)
Run Code Online (Sandbox Code Playgroud)
如果您的目标环境不支持对数组使用 findIndex,您可以使用其他一些方法来查找当前索引。一种是通过电话而不是身份证。
edit(phone) {
const currentIndex = this.phones.indexOf(phone);
// update using an api that returns the updated data.
var updatedPhone = update(phone.id)
this.phones.splice(currentIndex, 1, updatedPhone)
}
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,Vue 都会检测到更改并为您重新渲染。