vue.js - VueJS - 如何从另一个组件刷新表格组件?
问题描述
我有两个 Vue 组件:一个是表单,另一个是表格,它们在同一页面中。我想在提交表单时用新值刷新表格。
为了做到这一点,我需要调用从表单组件中获取数据并将其显示在表格上的函数,所以我需要跨两个不同的组件调用一个函数,我这样做了并且它可以工作。
问题是,虽然我可以从表单组件调用另一个组件中的函数,但表格不会用新值刷新,我该如何解决这个问题?
这是我的代码:
表单组件:
<template>
...
</template>
<script>
import axios from 'axios'
export default {
props:{
order:{
type:String,
default:'data'
},
},
mounted() {
console.log('Component mounted.')
},
data() {
return {
name: '',
description: '',
output: ''
};
},
methods: {
formSubmit(e) {
e.preventDefault();
console.log('Called fetchData!')
let currentObj = this;
axios.post('MYURL', {
'add_data': data,
})
.then(function (response) {
this.fetchData()
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
}
fetchData: function(){
this.$root.$emit('table_component')
},
}
}
</script>
表格组件:
<template>
<v-data-table
:headers="headers"
:items="customers"
:items-per-page="5"
:hide-default-footer="true"
class="elevation-1"
>
</v-data-table>
</v-container>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
search: '',
headers: [
{ text: 'Name', value: 'Name' },
{ text: 'Item', value: 'Item' },
],
customers: [],
}
},
mounted() {
this.fetchData()
this.$root.$on('table_component', () => {
this.fetchData()
},
},
methods: {
fetchData() {
fetch('MYURL')
.then(response => response.json())
.then(data => {
console.log(data)
this.customers = data;
})
},
}
}
</script>
这是我在这段代码中所做的:当提交表单并收到响应时,我调用函数fetchData()
。调用该函数是因为我看到console.log('Called fetchData!')
被触发了,所以它起作用了,唯一不起作用的是表没有用新值刷新。任何建议表示赞赏!
解决方案
似乎您在 then 函数中的上下文有问题
formSubmit(e) {
e.preventDefault();
console.log('Called fetchData!')
let currentObj = this;
axios.post('MYURL', {
'add_data': data,
})
.then((response) => {
this.fetchData()
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
}
您可以使用如上所示的箭头函数来调用 this.fetchData
或者你可以使用绑定
formSubmit(e) {
e.preventDefault();
console.log('Called fetchData!')
let currentObj = this;
axios.post('MYURL', {
'add_data': data,
})
.then(function (response) {
this.fetchData()
currentObj.output = response.data;
}.bind(this))
.catch(function (error) {
currentObj.output = error;
});
}
推荐阅读
- r - 如何在 R data.table 中有效地实现可变过滤条件?
- c# - 局部变量和类字段在运行时的行为差异
- background - 我如何知道用户是否从后台关闭了应用程序
- visual-studio-code - `workbench.action.terminal.switchTerminal` 有什么作用?
- object-storage - 使用 Curl 访问 IBM Bluemix 云对象存储
- javascript - 如果我将鼠标悬停在 javascript 中的一篇文章上,则激活一个功能
- rust - 如何解析带有嵌套参数的属性与亲爱的?
- html - 如何在对页眉、内容和页脚部分的动态/未知高度的内容使用 flex auto 时删除额外的 div 高度
- powershell - Foreach :过滤文件夹并匹配 stingue 和我们的时间跨度
- python - sm.current 不切换屏幕并给我属性错误:“str”对象没有属性“current”