如何在Vue.js页面加载后立即从localStorage中获取项目?

huangapple go评论55阅读模式
英文:

How do I get item from localstorage immediately after page loads in vue js?

问题

这是我的存储:
如何在Vue.js页面加载后立即从localStorage中获取项目?
我获取名为 selectedResultIsLCC 的值为 true 的变量 selectedResultIsLCC

这是我的脚本:

computed: {
  isLCC() {
    return localStorage.getItem("selectedResultIsLCC") === "true";
  },
},

这是我的模板:

<div>
    <div
      v-if="isLCC"
      @click="sendTicketRequest"
    >
        立即预订LCC
    </div>
    <div
      v-else
      @click="sendBookRequest"
      >
        立即预订-LCC
      </div>
   </div>
</div>

在我看到模板中的 v-if 返回 true 之前,我必须进行强制刷新。

请问我应该如何处理这个问题,如何在页面加载时立即获取存储中的项目。

英文:

This is my storage:
如何在Vue.js页面加载后立即从localStorage中获取项目?
I get selectedResultIsLCC with value &quot;true&quot;

This is my script:

computed: {
  isLCC() {
    return localStorage.getItem(&quot;selectedResultIsLCC&quot;) === &quot;true&quot;;
  },
},

This is my template:

&lt;div&gt;
    &lt;div
      v-if=&quot;isLCC&quot;
      @click=&quot;sendTicketRequest&quot;
    &gt;
        Book Now (LCC)
    &lt;/div&gt;
    &lt;div
      v-else
      @click=&quot;sendBookRequest&quot;
      &gt;
        Book Now (Non-LCC)
      &lt;/div&gt;
   &lt;/div&gt;
&lt;/div&gt;

I have to hard refresh before I see v-if in template which returns true in my storage.

Please how do I go about this, how can I get the item in my storage immediately the page loads.

答案1

得分: 1

使用 `created`  `mounted` 生命周期最好将变量存储在 Vue 的数据中

```vue
&lt;script&gt;
    export default {
        data() {
            return {
                isLCC: false
            };
        },
        created() {
            this.isLCC = localStorage.getItem("selectedResultIsLCC") === "true";
        },
    };
&lt;/script&gt;
英文:

Use created or mounted lifecycle and it's better store variables in vue data:

&lt;script&gt;
    export default {
        data() {
            return {
                isLCC: false
            };
        },
        created() {
            this.isLCC = localStorage.getItem(&quot;selectedResultIsLCC&quot;) === &quot;true&quot;;
        },
    };
&lt;/script&gt;

huangapple
  • 本文由 发表于 2023年7月18日 04:10:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定