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 - VueJS 通过挂载的事件监听器监听组合键

webpack - 引用错误: webpackJsonp is not defined

vue.js - vue 将字符串渲染为已存在的组件

docker - 使用 docker 镜像在 Heroku 上部署 Go App + Vue.js

javascript - 如何通过javascript访问Topaz Signature Pad ActiveX对象?

javascript - POST 成功后 Ajax 重定向到另一个页面

javascript - 在单文件组件中使用 Vue.js 插件

javascript - 在父组件中增加子组件时如何更新子组件?

javascript - 带有 FrameSet 的 Tinymce 不工作?

javascript,多态 new Myclass()?