我有一个 computed
方法:
computed: {
currentPosition () {
if(this.get_local_storage_state()){
return this.lastLocation
}
if (this.currentRestaurant) {
return this.currentRestaurant.address.location
} else if (this.searchPosition.lat && this.searchPosition.lon) {
return this.searchPosition;
} else {
return null;
}
}
}
在我的 <template>
中被调用:
<GMap class="c-splitview__map" :markers="getMarkers" :position="currentPosition" :zoom="currentZoom" v-if="currentPosition" />
<div class="m-storefinder__placeholder" v-else>
<h1 class="o-headline">{{$tc("storefinder.emptyDeeplink")}}</h1>
</div>
出于某种原因,当它第一次被调用时,它会正常工作,但是当我尝试再次调用它(重新渲染 Vue 组件)时,它不会被调用。
但是!
当我注释掉第一个 if()
声明,像这样:
computed: {
currentPosition () {
// if(this.get_local_storage_state()){
// return this.lastLocation
// }
if (this.currentRestaurant) {
return this.currentRestaurant.address.location
} else if (this.searchPosition.lat && this.searchPosition.lon) {
return this.searchPosition;
} else {
return null;
}
}
}
它再次正常工作。
this.get_local_storage_state()
函数看起来像这样,位于 methods:{}
:
get_local_storage_state(){
let state = localStorage.getItem('McDonaldsStoreWasOpen');
return state === "true" ? true : false;
}
我基本上是在尝试使用本地存储作为状态管理系统。
最佳答案
localStorage
不是响应式(Reactive)的,无法观察到。这与计算值被缓存的事实相结合,意味着当您将值从计算中的本地存储中提取出来时,结果将被缓存并且计算后将始终返回相同的值那。这也是当您从 localStorage
中删除值时计算恢复工作的原因。
我建议您从 localStorage
初始化一个数据值,在您的计算中使用该值,然后在稍后指定的时间将该值保存回 localStorage
时间。
这是一个codepen demonstrating区别。
关于javascript - Vue 计算方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46695669/