我有一个表应该不断更改其数据。当单击父组件中的按钮时,将调用服务器,然后通过 prop 将 json 文件加载到子组件(表格)中。
每当单击不同的按钮并且表需要重新加载数据时,事实并非如此。我尝试过这样做:
this.$refs.dmTable.refreshTable();
和
this.$forceUpdate()
我的代码的粗略结构:
Parent.vue
<template>
<Button getData("this")>Get This Data</Button>
<Button getData("that")>Get ThatData</Button>
<MyTable v-if="showTable" :data="data" />
<template>
<script>
export default {
data(){
return{
showTable:false,
data: null
}
},
methods:{
getData(dataType){
getDataFromServer(dataType).then(data =>{
this.data = data.body
this.showTable = true
})
}
}
}
</script>
MyTable.vue
<template>
<b-table :items="data"><b-table/>
</template>
<script>
export default{
props: ["data"]
}
</script>
如果单击第一个按钮,数据将正常加载到表中。但是,如果您单击第二个按钮并尝试将新数据加载到表中,则不会发生任何情况。我尝试在包含
updateTable()
的子组件中创建一个名为 this.$refs.myTable.update()
的方法,但它什么也没做。
编辑: 需要注意的一件事是,我加载到此表中的数据非常大,有 5mb json 文件。
实际被调用的函数:
showTableView(model, type) {
request
.get(
`/table_files/${this.folder_name}/${model}.json`
)
.then(response => {
this.type = type;
this.current_model = model;
if (type === "joins") {
this.tlorderData = response.body.fields.joins;
this.show_joins_table = true;
this.showTable = false;
this.refreshTable()
return false; // MAYBE RETURNING FALSE BREAKS THE RERENDERING?
}
else if (type === "dimension_groups") {
this.show_joins_table = false;
this.showTable = true;
this.tlorderData = response.body.fields.dimension_groups;
this.refreshTable()
return false;
}
})
.catch(err => {
this.response_error = err;
});
},
我看不到您在主应用程序组件中定义
data
和 showTable
的位置。将 this.data
设置为值不是反应性的(它正在应用程序组件上创建非反应性属性)。
试试这个:
<template>
<Button @click="getData('this')">Get This Data</Button>
<Button @click="getData('that')">Get ThatData</Button>
<MyTable v-if="showTable" :data="data" />
<template>
<script>
export default {
data() {
return {
data: [],
showTable: false
}
},
methods:{
getData(dataType){
getDataFromServer(dataType).then(data =>{
this.data = data.body
this.showTable = true
})
}
}
}
</script>
data()
部分将定义data
和showTable
作为应用程序/组件实例上的响应式属性。
问题出在我的代码中没有提到的地方。 我将数据加载到表中的方式是这样的:
<template>
<b-table :items="reData"><b-table/>
</template>
<script>
export default{
props: ["data"],
data(){
return{
reData: this.data
}
}
}
</script>
这会阻止我的表在 prop 中的数据发生更改时更新,请注意,我将 prop 传递给
data()
,然后将其传递到我的表中。因此道具会改变,但表格显示的实际数据不会改变。
从道具传递到表以防止这种情况发生的正确方法:
<template>
<b-table :items="data"><b-table/>
</template>
<script>
export default{
props: ["data"]
}
</script>