我来自 vue,习惯于可组合的功能。我试图找出在苗条中做到这一点的方法
所以我制作了一个 js 文件并导入存储,然后尝试制作一个可以调用多个组件并单独操作的函数
swipe.js 文件
import { writable, derived, get } from 'svelte/store';
function createSwipe() {
const dyFromStart = writable(0)
function moveEvent(eventType, val){
console.log('moveEvent', eventType, val, get(dyFromStart))
dyFromStart.update(n => n + 1);
}
const dxScore = derived(dyFromStart, $dyFromStart => $dyFromStart + 3)
const dyScore = derived(dyFromStart, $dyFromStart => Math.round($dyFromStart + 100));
return {
moveEvent,
dxScore,
dyScore,
};
}
export const swipe = createSwipe();
然后在脚本中的.svelte组件导入函数中分解成子部分
<script>
import { swipe } from "$lib/swipe";
let { moveEvent, dxScore, dyScore } = swipe
</script>
<p>{$dxScore}{$dyScore}</p>
<button on:click="() => moveEvent">button</button>
好吧,最终我想变成一个滑动组件,因此得名,但试图降低基本面。因此,我希望能够为每个组件拥有唯一的存储,为此,如果我使用多个此 .svelte 组件,则状态将在所有人之间共享。
不仅仅是三个 idk modal.svelte 组件,我想对一堆差异组件使用滑动,也许是 photoViewer.svelte 只是通用滑动功能,并且对所有组件使用相同的代码。
还是我只需要保持每个 .svelte 组件中的状态const dyFromStart = writable(0)
并将let dyFromStart = 0
其传递给一个纯 js 函数,该函数返回结果并更新本地 .svelte 变量
将其添加为我正在尝试但无法响应的非存储更纯 js 的东西,因此接受下面关于存储方法的答案,听起来像是正确的方法
export function createSwipe() {
let dyFromStart = 0
function moveEvent(eventType, val){
console.log('moveEvent', eventType, val, dyFromStart, dxScore(), dyScore())
dyFromStart++
}
function dxScore(){ return dyFromStart + 3 }
// const dzScore = derived(dyFromStart, $dyFromStart => $dyFromStart + 3)
const dyScore = () => Math.round(dyFromStart + 100)
return {
moveEvent,
dxScore,
dyScore,
dyFromStart
};
export function createSwipe() {
let dyFromStart = 0
let dxScore = dyFromStart + 3
let dyScore = Math.round(dyFromStart + 100)
function moveEvent(eventType, val){
console.log('moveEvent', eventType, val, dyFromStart, dxScore, dyScore)
dyFromStart++
dxScore = dyFromStart + 3
dyScore = Math.round(dyFromStart + 100)
}
return {
moveEvent,
dxScore,
dyScore,
dyFromStart
};
我想这可以正常工作,只是不会与 $ 反应,如果这样做需要调用来更新 diff local var
就可组合函数类型样式而不是存储类型而言,这对我来说似乎最苗条或类似的东西
export function createSwipe() {
let dyFromStart = 0
function moveEvent(eventType, val){
console.log('moveEvent', eventType, val)
dyFromStart++
}
$: dxScore = dyFromStart + 3
$: dyScore = Math.round($dyFromStart + 100)
return {
moveEvent,
dxScore,
dyScore,
};
}