vue实现表格刷新
Vue 实现表格刷新的方法
使用 v-if 强制重新渲染
通过 v-if 控制表格的显示与隐藏,切换时 Vue 会重新渲染组件。
<template>
<button @click="refreshTable">刷新表格</button>
<table v-if="showTable">
<!-- 表格内容 -->
</table>
</template>
<script>
export default {
data() {
return {
showTable: true
}
},
methods: {
refreshTable() {
this.showTable = false
this.$nextTick(() => {
this.showTable = true
})
}
}
}
</script>
修改 key 强制更新
为表格绑定动态 key,改变 key 值会触发组件重新渲染。
<template>
<button @click="refreshTable">刷新表格</button>
<table :key="tableKey">
<!-- 表格内容 -->
</table>
</template>
<script>
export default {
data() {
return {
tableKey: 0
}
},
methods: {
refreshTable() {
this.tableKey += 1
}
}
}
</script>
通过数据更新驱动刷新
直接更新表格绑定的数据源,Vue 的响应式系统会自动更新视图。
<template>
<button @click="refreshTable">刷新表格</button>
<table>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: []
}
},
methods: {
async refreshTable() {
const res = await fetch('/api/data')
this.tableData = await res.json()
}
}
}
</script>
使用 $forceUpdate 方法
强制组件重新渲染,适用于数据更新但视图未响应的情况。
<template>
<button @click="refreshTable">刷新表格</button>
<table>
<!-- 表格内容 -->
</table>
</template>
<script>
export default {
methods: {
refreshTable() {
this.$forceUpdate()
}
}
}
</script>
结合 Vuex 状态管理
通过 Vuex 管理表格数据,提交 mutation 或 action 更新数据。
// store.js
export default new Vuex.Store({
state: {
tableData: []
},
mutations: {
updateTableData(state, payload) {
state.tableData = payload
}
},
actions: {
async fetchTableData({ commit }) {
const res = await fetch('/api/data')
commit('updateTableData', await res.json())
}
}
})
<template>
<button @click="refreshTable">刷新表格</button>
<table>
<tr v-for="item in $store.state.tableData" :key="item.id">
<td>{{ item.name }}</td>
</tr>
</table>
</template>
<script>
export default {
methods: {
refreshTable() {
this.$store.dispatch('fetchTableData')
}
}
}
</script>
注意事项
- 数据驱动更新是 Vue 推荐的方式,优先考虑通过修改数据实现刷新
v-if和key方法会触发组件完全重新渲染,可能影响性能$forceUpdate不会更新子组件,仅强制当前组件重新渲染- 大型项目建议使用 Vuex 或 Pinia 集中管理状态







