javascript - 使用 vue-router 在 Vue.js 中存储数据
问题描述
我有一个 Vue.js 项目,它安装了 vue-router 来控制“页面”和 axios 以调用 API。
这是我的路线
routes: [
{
path: '/',
name: 'LandingPage',
component: LandingPage
},
{
path: '/test',
name: 'test',
component: testing
}
]
在 testingPage 中,我将调用 API 来获取渲染页面的数据。
<template>
<div>
{{title}}
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'app',
data: function () {
return {
result: [],
title:""
}
},
methods: {
fetchResult: function () {
axios.get('https://jsonplaceholder.typicode.com/todos/1').then((response) => {
this.result = response;
this.title = response.data.title
console.log(response);
}, (error) => {
console.log(error)
})
}
},
mounted: function () {
this.fetchResult()
}
}
</script>
但是这里出现问题时,每次使用单击链接并重定向到此“页面”时,都会调用该 api。API 每月只会更新 1-2 次。
我可以只调用一次,然后存储结果并使其不会再次调用 API,直到使用刷新页面或在新的浏览器/选项卡中打开页面?
解决方案
用vuex怎么样?在挂载主应用程序时(它只会挂载一次。),您可以将数据存储在 vuex 商店中。
另外,如果您想将状态保持在多个选项卡中,我建议您使用localStorage
.
看看这个:Multiple Tab LocalStorage 单用户用例
还有 vuex + localstorage 的库: https ://www.npmjs.com/package/vuex-localstorage
推荐阅读
- c++ - 在头文件中使用“朋友”和“模板”
- javascript - Docker Compose + Jest - 测试输出未显示在控制台中
- php - 发布数据时php没有得到完整的url
- r - 在ggplot中端到端覆盖geom_col
- java - 包 android.os 不存在(使用 JDK 11 编译时)
- java - 如何从方法返回二维数组
- security - 数字签名是否确保整个消息都被加密?
- node.js - 如何在前端离子角度项目中导入缓冲区库以使 node-rsa 工作
- python - LSTM 层构建收到警告
- oracle - 根据参数 -Oracle 重新启动 sum(over) 函数