У меня есть динамический список [Когда я создаю массив, и когда пользователь вводит любой текст, он создает для него новый проект и печатает его с другим проектом на экране].
Когда страница открыта (загружена впервые), программа отправит HTTP-запрос на сервер, чтобы принести все проекты для текущего пользователя и распечатать их ... и на той же странице у меня есть поле ввода и все проекты для текущий пользователь перечислен вниз. когда пользователь пытается добавить новый проект в свой список, HTTP-запрос успешно добавляется в список [но не отображается на странице, если я обновляю страницу, то новый проект добавляется в список]
Мой код следующий:
В <script>
:
export default {
name: "Projects",
data: function() {
return {
Projects: [],
ProjectName:'',
Username:''
}
},
created(){
this.GetAllProjects(); //print all Projects.
},
methods: {
CreateNewProject: function() {
var app = this; var idNo = XXXXX; var username= XXXXX;
axios({
method: "post",
timeout: 3000,
headers: {
.......
},
url: "XXXXXXX", data: {
name: app.ProjectName,
username: username,
}
})
.then(function(response) {
console.log(response);
app.ProjectName = "";
})
.catch(function(error) {
console.log(error);
});
},
GetAllProjects: function(){
var app = this; app.id = XXXX; app.Username= XXXX;
const instance = axios.create({
timeout: 3000,
headers: {
......
}
});
instance.get("XXXXX")
.then( function(response) {
console.log(response);
Object.keys(response.data.result).forEach( function (product) {
console.log(response.data.result[product]);
console.log('product number: ' + product);
var subscribersCounter = 0;
//Save the response required results into a struct.
let example = {
name: response.data.result[product].name,
id: response.data.result[product].id,
subscribers: response.data.result[product].subscribers,
products: response.data.result[product].products,
};
//Create an object for the current Project.
let uploadedExample = {
name: '',
id: '',
subscribers: '',
products: {name:'',color:''},
};
uploadedExample.name = example.name; //name of the current workspace.
uploadedExample.id = example.id; //id of the current workspace.
//Check if the subscribers empty or not, if not empty count the available subscribers.
if ( example.subscribers ) {
Object.keys(example.subscribers).forEach(function (key) {
subscribersCounter++;
});
}
uploadedExample.subscribers = subscribersCounter; //subscribers No. of the current workspace.
console.log("Total subscribers: " + uploadedExample.subscribers);
//Check if the products empty or not, if not empty count the available products.
if ( example.products ) {
Object.keys(example.products).forEach(function (Pkeys) {
uploadedExample.products.name = Pkeys; //name of the product in the current workspace.
Object.keys(example.products[Pkeys]).forEach(function (key) {
if (key == 'color') {
uploadedExample.products.color = example.products[Pkeys][key]; //color of the product in the current Project.
}
});
});
}
//add the new workspace to the list of Projects.
app.Projects.push(uploadedExample);
});
})
.catch(function(error) {
console.log(error);
});
}
}
}
In <tamplete>
:
<b-col v-for="(project,index) in Projects" :key="index">
<b-row><h1> {{project.name}} </h1></b-row>
..........
То, что я сделал, это:
когда страница загружается, процесс получения всех проектов для пользователя творится, и выводишь их на экран. и когда пользователь пытается добавить новый проект, это делается успешно. единственное, когда он добавил проект, я хочу отправить HTTP-запрос и в то же время добавляет этот проект в список, напечатанный на экране, без необходимости обновления страницы пользователем.
Примечание: Я использую location.reload();
, но не то, что я хочу.
Примечание: Мне нужно получить все проекты из HTTP-запроса, потому что мне нужны некоторые данные для их обработки, поэтому добавление имени проекта в массив проектов, которые будут напечатаны на экране, не поможет я.