VueJS/Vuetify - @change set load= "true" on input



我正在尝试创建一个方法,该方法由@change在多个输入上触发。

我需要为目标输入设置loading="true",直到axios完成请求(PATCH(。

注:

页面上有多个v-select,我想仅针对一个特定目标(当前输入/选择(设置loading=true。


示例:

如果用户在下面的示例中的第一个选择中选择了一个选项,则调用inlineUpdate方法,该方法将目标修改为类似于<v-select loading="true" @change="$root.inlineUpdate" ...

然后,在update完成之后,它移除loading属性。


我想我需要将event参数传递到方法中,但它不起作用。

它只传递一个值,所以我无法识别应该将哪个输入设置为加载。

<v-select @change="$root.inlineUpdate" ...
<v-select @change="$root.inlineUpdate" ...
<v-select @change="$root.inlineUpdate" ...
<v-text-field @change="$root.inlineUpdate"...
inlineUpdate(event){
console.log(event)
console.log(event.target)
# here I need to set loading="true" for the input
axios.post(...).finally(() => { // remove the loading })
# stop loading
},

记录

>>> house
>>> undefined

有没有办法做到这一点?

您需要创建一个单独的变量,只处理v-select的加载。因此,我们创建了一个名为isSelectLoading的,默认为false。然后,当我们开始API调用过程时,我们将其设置为true,一旦promise解析,我们就将其设置回false

<v-select label="Typ nehnuteľnosti" :loading="isSelectLoading"  @change="$root.inlineUpdate" ...
...
data: () => ({
isSelectLoading: false
}),
methods: {
inlineUpdate(){
this.isSelectLoading = true;
axios.put("/some/url", ...)
.then(apiResponse => { //do some stuff })
.catch(apiError => { //oh no! })
.finally(() => { this.isSelectLoading = false });
},
}

更新多个v-selects

您需要一种方法来跟踪正在加载的组件。我们将使用一个名为isSelectLoading的数组来处理此问题。它将在我们的数据属性中,并且我们默认加载状态为false

您还需要知道哪个v-select正在更改。为了解决这个问题,我们将创建另一个名为activeSelect的变量。我们将通过@click事件侦听器将其绑定到我们的v-select

然后,当我们从任何选择中更改选择时,我们只能更新该v-select的加载状态!

<v-select 
@change="inlineUpdate" 
@click="activeSelect = 0"
:loading="isSelectLoading[0]"...
<v-select 
@change="inlineUpdate" 
@click="activeSelect = 1"
:loading="isSelectLoading[1]"...
<v-select 
@change="inlineUpdate" 
@click="activeSelect = 2"
:loading="isSelectLoading[2]"...
<v-text-field
@change="inlineUpdate" 
@click="activeSelect = 3"
:loading="isSelectLoading[3]"...
...
data: () => ({
activeSelect: null,
items: ["a", "b", "c"],
isSelectLoading: [false, false, false]
}),
methods: {
inlineUpdate(){
this.toggleLoading(this.activeSelect);
axios.put("/some/url", ...)
.then(apiResponse => { //do some stuff })
.catch(apiError => { //oh no! })
.finally(() => { this.toggleLoading(this.activeSelect); });
},
toggleLoading(index) {
this.isSelectLoading[index] = !this.isSelectLoading[index]
}

在这个例子中,它有点琐碎化;在实际代码中,我们可以将这些放在<template v-for="(item, index) in selects">...中,其中selects将具有生成所选组件所需的字段/属性。您可以将硬编码的索引替换为事件绑定的值index

最新更新