2017-10-11 112 views
2

我有一個computed方法:Vue的計算方法沒有得到所謂的

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; 
} 

我基本上是試圖使用本地存儲的狀態管理系統。

+0

可能重複的[localStorage和布爾'字符串'](https://stackoverflow.com/questions/30644250/localstorage-and-boolean-string) – Terry

回答

5

localStorage沒有反應且無法觀察。這與計算值緩存這一事實相結合意味着,當您將值從計算中的本地存儲中提取出來時,結果將被緩存,並且計算結果將始終返回相同的值。這也是爲什麼當您從localStorage中刪除該值時,計算機繼續工作。

我會建議您改爲從localStorage初始化數據值,在計算出的值中使用該值,然後在稍後的指定時間將值保存回localStorage

這是codepen demonstrating的區別。

+0

好吧我理解與localstorage的問題,但不知道解決方案你建議在這種情況下應用,因爲計算出的方法取決於我正在註釋的'if()'語句的結果。 – Jousi

+0

@Jousi我更新了示例筆,以便被動示例使用計算結果,該計算結果不是數據值而是本地存儲值。 – Bert

相關問題