Vue计算方法没有被调用

Jou*_*usi 2 javascript state vue.js computed-properties vuejs2

我有一个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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

哪个在我的电话中被调用<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>
Run Code Online (Sandbox Code Playgroud)

并且出于某种原因,当它第一次被调用时,它的运行方式应该如何,但是当我再次尝试调用它时(重新渲染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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

它的工作原理应该如何.

this.get_local_storage_state()函数如下所示,位于methods:{}:

get_local_storage_state(){
  let state = localStorage.getItem('McDonaldsStoreWasOpen');
  return state === "true" ? true : false;
}
Run Code Online (Sandbox Code Playgroud)

我基本上试图使用本地存储作为状态管理系统.

Ber*_*ert 6

localStorage不是反应性的,不能被观察到.这与计算值被缓存的事实相结合意味着当您从计算中的本地存储中提取值时,结果将被缓存,并且计算后将始终返回相同的值.这也是当你从中删除值时计算恢复工作的原因localStorage.

我建议您初始化数据值localStorage,在计算中使用该值,然后将值保存回localStorage以后指定的时间.

这是一个展示差异的代码.