首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue计算方法不被调用

Vue计算方法不被调用
EN

Stack Overflow用户
提问于 2017-10-11 18:59:11
回答 1查看 1.1K关注 0票数 2

我有一个computed方法:

代码语言:javascript
复制
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>中被呼叫

代码语言:javascript
复制
<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()语句时,如下所示:

代码语言:javascript
复制
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:{}

代码语言:javascript
复制
get_local_storage_state(){
  let state = localStorage.getItem('McDonaldsStoreWasOpen');
  return state === "true" ? true : false;
}

我基本上是试图使用本地存储作为一个国家管理系统。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-11 19:17:46

localStorage不是反应性的,不能被观察到。这与计算值被缓存的事实相结合,意味着当您从计算中的本地存储中提取值时,结果将被缓存,并且计算后总是返回相同的值。这也是为什么在从localStorage中删除值时计算的简历工作的原因。

相反,我建议您从localStorage初始化一个数据值,在计算中使用该值,然后在稍后指定的时间将该值保存回localStorage

这是一个代码演示的区别。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46695669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档