gpt4 book ai didi

javascript - Vue.js:数据不是 react 性的,并且在方法内没有正确更新

转载 作者:行者123 更新时间:2023-11-28 12:54:34 24 4
gpt4 key购买 nike

我有一个自定义组件,它接收过滤器列表,以便仅显示用户选择的医生:

<DoctorsSidebarFilter @update-view='showFilteredDoctors'></DoctorsSidebarFilter>

接下来,在我的主要组件中,我使用它来显示医生:

<v-flex
v-for="doctor in allDoctors"
:key="doctor.first_name"
xs12
sm6
md4
>

这是我的数据:

export default {
data: () => ({
allDoctors:[],
}),
methods: {
fetchDoctors(){
//Retrieve doctors
this.$store.dispatch(RETRIEVE_DOCTORS)
.then(
response => {
this.allDoctors = response;
}
)//TODO-me: Handle the error properly!
.catch(error => {
console.log(error);
});
},
showFilteredDoctors(filters){
let result = [];
this.fetchDoctors();

console.log('1:' + " " + JSON.stringify(this.allDoctors));
if (filters.length > 0) { // If Array is not empty then apply the filters
console.log('2');
this.allDoctors.forEach(function(e) {
if(filters.some(s => s.specialty === e.specialty || s.city === e.city)) {
result.push(e);
}
});
console.log('3:' + " " + JSON.stringify(result));
this.allDoctors = [...result];
console.log('4:' + " " + JSON.stringify(this.allDoctors));
}
}
},
mounted() {
this.fetchDoctors();
}
}

问题是,尽管我的过滤工作正常,并且我可以从 console.log('4:' + ""+ JSON.stringify(this.allDoctors)); 中看到 this.allDoctors 包含新的过滤列表;这永远不会显示在屏幕上。

相反,我看到的是从 API 获取的默认医生列表。使用 vue devtools,我可以看到 this.allDoctors 暂时更新为正确的值,但随后又恢复为默认值。

最佳答案

正如 @user1521685 已经解释的那样,对 fetchDoctors 的调用是异步的,因此它会在您执行过滤后完成。

通常,您会使用计算属性来执行类似的操作,并且只调用服务器一次。

export default {
data: () => ({
allDoctors: [],
filters: []
}),
computed: {
filteredDoctors() {
const allDoctors = this.allDoctors;
const filters = this.filters;

if (filters.length === 0) {
return allDoctors;
}

return allDoctors.filter(doctor => {
return filters.some(filter => filter.specialty === doctor.specialty || filter.city === doctor.city);
});
}
},
methods: {
fetchDoctors(){
//Retrieve doctors
this.$store.dispatch(RETRIEVE_DOCTORS)
.then(
response => {
this.allDoctors = response;
}
)//TODO-me: Handle the error properly!
.catch(error => {
console.log(error);
});
},
showFilteredDoctors(filters){
this.filters = filters;
}
},
mounted() {
this.fetchDoctors();
}
}

在您的模板中,您可以使用:

v-for="doctor in filteredDoctors"

关于javascript - Vue.js:数据不是 react 性的,并且在方法内没有正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56921280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com