我一直在尝试在svelte中创建身份验证系统,并且注册是一个多步骤过程,因此需要保存步骤1中的api响应并继续进行,每个步骤都是一条不同的路线.svelte中遇到了store
使用undefined
获取数据时,它仅返回get
。下面是返回相同输出的演示代码。
索引
<script>
import signUpStore from "./hobby-store.js";
let data = {
name: "Rahul",
age: "something"
};
signUpStore.setSignUp(data);
// let result = signUpStore.getSignUp();
// console.log(result); //undefined
</script>
<p>
<strong>
Try editing this file (src/routes/index.svelte) to test live reloading.
</strong>
</p>
关于斯维尔特
<script>
import signUpStore from "./hobby-store.js";
import { onMount } from "svelte";
let result = signUpStore.getSignUp();
console.log("server side : ", result); //undefined
onMount(() => {
console.log("client side : ", result); // undefined
});
</script>
<p>This is the 'about' page. There's not much here.</p>
hobby-store.js
import {
writable,
get
} from 'svelte/store'
const signUp = writable()
const signUpStore = {
subscribe: signUp.subscribe,
setSignUp: (items) => {
signUp.set(items)
// console.log('items : ', items, signUp)
},
addSignUp: (data) => {
signUp.update(items => {
return items.concat(data)
})
},
getSignUp: () => {
get(signUp)
}
}
export default signUpStore;
只需要将这些数据保存在会话或svelte或sapper提供的任何持久性存储中,然后在成功执行操作后将其重置。
最佳答案
下面的示例session.js存储并记录日志:
import { writable } from 'svelte/store';
import { deepClone } from './../utilities/deepClone.js';
const newSession = {
a; 0, b: 0, x: 0
};
function sessionStore() {
const { subscribe, set, update } = writable(deepClone(newSession));
let logging = false;
return {
subscribe, // $session...
update: (obj) => {
update(o => { // session.update({a:1, b:2});
const merged = Object.assign(o, obj);
if (logging) console.log('session update', merged);
return merged;
});
},
set: (key, value) => { // session.set('x', 9)
update(o => {
const merged = Object.assign(o, {[key]: value});
if (logging) console.log('session set', merged);
return merged;
});
},
reset: () => { // session.reset()
set(deepClone(newSession));
},
set log(bool) { // setter: session.log = true;
logging = bool === true;
}
};
};
export const session = sessionStore();
Example.svelte
<script>
import { session } from './session.js';
session.log = true;
$: console.log('reactive log', $session);
session.set('x', 10);
session.reset();
<script>
关于javascript - Svelte/Sapper-无法保存来自其他路线上api响应的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60734045/