javascript - Vue 计算方法未被调用

标签 javascript vue.js vuejs2 state computed-properties

我有一个 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/

相关文章:

javascript - 在 Javascript 中创建事件

javascript - 为什么设置 scrollTop 无法设置正确的位置?

javascript - Vue.js 嵌套 for 循环与搜索过滤器

vue.js - 单击操作不适用于 vuetify 徽章

html - 单击后 Vue.js 图像映射禁用区域

javascript - Heroku:找出哪个文件夹是活的

javascript - 使用 Express 提交 post 请求后如何保持在同一页面?

javascript - Vue JS 将下一个输入集中在 enter 上

javascript - 为每 3 个项目创建一个新行 Vue.js

webpack - Vue.js 2.0 模块构建失败 : SyntaxError: Unexpected token using webpack, Elixir 和 gulp