【问题标题】:How to store/cache request data from CMS in Vue3?如何在 Vue3 中存储/缓存来自 CMS 的请求数据?
【发布时间】:2021-12-15 15:57:30
【问题描述】:

我在Vue3/Laravel8 app 中使用Laravel Nova 构建了一个原始Content Management System。作为菜鸟,我使用axios.get 从database 获取图像链接和降价,并将其分配给reactive state,如下所示:

<script setup>
import {reactive} from 'vue';
import DOMPurify from "dompurify";
import marked from "marked";

const state = reactive({
    locale: sessionStorage.locale,
    content: "",
    image: ""
})

axios.get('/home')
    .then(res => {
        const data = res.data[0]
        state.content = DOMPurify.sanitize(marked(data['content_' + state.locale]))
        state.image = 'storage/' + data['image']
    })
    .catch(err => {
        console.log(err);
        console.log(err.response);
    });

</script>

并在我的模板中渲染image/markdown:

<template>
  <section id="home" class="home">
    <div class="home-image" :style="{'background-image': 'url(' + state.image + ')'}"></div>
    <div v-html="state.content"></div>
  </section>
</template>

这会产生两个问题:

  1. 每次刷新或加载页面时,应用程序都必须等待response。
  2. 每次刷新或加载页面时都会呈现images/content。

有没有办法缓存response data?我只需要存储string information。

我已尝试使用 sessionStorage 执行此操作,但在初始页面加载期间它不适用于 state = reactive()(或者有办法吗?)。

【问题讨论】:

    标签: laravel vue.js axios vuejs3 laravel-nova


    【解决方案1】:

    是的,您可以使用localStorage 或sessionStorage 来实现此目的。只需在设置时将对象转为字符串,在使用时转回即可。

    例子:

    ...
      const setState = data => {
        state.content = DOMPurify.sanitize(marked(data['content_' + state.locale]))
        state.image = 'storage/' + data['image']
      }
    
      if (localStorage.getItem('home')) {
        const data = JSON.parse(localStorage.getItem('home'))
        setState(data[0])
      } else {
        axios.get('/home')
          .then(res => {
            localStorage.setItem('home', JSON.stringify(res.data))
            setState(res.data[0])
          })
      }
    ...
    

    JSFiddle

    【讨论】:

    • 但这不会是reactive 吧? ss/ls 没有反应。
    • 不相关。 localStorage 仅在我们获取字符串并将其设置回反应对象时存储它,它仍然是反应对象,除非您执行以下操作:state = ...。您可以从小提琴中看到,如果不是反应式的,它不会改变内容。
    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 2021-10-13
    • 2014-01-18
    相关资源
    最近更新 更多