![](/img/trans.png)
[英]How can I transmit from a component to another when redirecting in VueJS?
[英]VueJS - How can i refresh a table component from another component?
我有兩個 Vue 組件:一個是表單,另一個是表格,它們在同一頁面中。 我想在提交表單時用新值刷新表格。
為了做到這一點,我需要調用 function 從表單組件中獲取數據並將其顯示在表格上,所以我需要跨兩個不同的組件調用 function,我做到了並且它有效。
問題是,雖然我可以在表單組件的另一個組件中調用 function,但表格不會用新值刷新,我該如何解決這個問題?
這是我的代碼:
表單組件:
<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>
這是我在這段代碼中所做的:當提交表單並收到響應時,我調用 function fetchData()
。 調用 function 是因為我看到console.log('Called fetchData!')
被觸發,所以它起作用了,唯一不起作用的是表沒有用新值刷新。 任何建議表示贊賞!
似乎您在當時的 function 中的上下文有問題
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;
});
}
您可以使用如上所示的箭頭 function 來調用 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;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.