在 Svelte 中从 onstate() 更新数据
Updating data from onstate() in Svelte
我刚开始使用 Svelte/Sapper,但我没有理解这件愚蠢的事情。可能是用惯了Vue,对Svelte的范式不了解。
我基本上是在制作滑块或旋转木马。为此,我需要知道要显示的当前部分是什么(这将有助于确定进入动画)并记录上一节(只要它需要过渡出去)。
我想我可以有一个
<button on:click="set({ section: 'products'})">Go to Products</button>
切换部分,这很好用。但是后来我想在 onstate() 中进行检测,以便在更改部分时,道具 prevSection 也会更新。
这是我目前拥有的(相关)代码:
<h1>Current section : {section}</h1>
<button on:click="set({ section: 'products'})">Go to Products</button>
<button on:click="set({ section: 'hr'})">Go to HR</button>
<button on:click="set({ section: 'verticals'})">Go to Verticals</button>
<div id="container">
<Slideshow bind:section></Slideshow>
<Slideshow bind:prevSection></Slideshow>
</div>
<style>/* Not important */</style>
<script>
export default {
onstate({ changed, current, previous }) {
if (changed.section && previous) {
this.set({prevSection: previous.section});
}
},
oncreate() {},
onupdate() {},
ondestroy() {},
components: {
Slideshow: '../components/Slideshow.html'
},
data() {
return {
section : 'products',
prevSection : ''
};
}
}
</script>
我想要一个初始状态,其中 section=products 且 prevSection 为空,然后每次单击按钮时,prevSection 获取 section 的值,然后 section 更新为由按钮。
非常感谢您的帮助!
不确定这是否是您要查找的内容,但我能够通过将逻辑从 onstate 移动到 onupdate
在您的示例中正确更新 section 和 prevSection 变量
原来问题不在于代码本身,而是
<Slideshow bind:prevSection></Slideshow>
显然正在接收 prevSection 道具,但我试图 console.log() section 属性。所以代码有点工作,我只是检查了错误的道具。
感谢所有花时间回答甚至只是看一下的人!
我刚开始使用 Svelte/Sapper,但我没有理解这件愚蠢的事情。可能是用惯了Vue,对Svelte的范式不了解。
我基本上是在制作滑块或旋转木马。为此,我需要知道要显示的当前部分是什么(这将有助于确定进入动画)并记录上一节(只要它需要过渡出去)。
我想我可以有一个
<button on:click="set({ section: 'products'})">Go to Products</button>
切换部分,这很好用。但是后来我想在 onstate() 中进行检测,以便在更改部分时,道具 prevSection 也会更新。
这是我目前拥有的(相关)代码:
<h1>Current section : {section}</h1>
<button on:click="set({ section: 'products'})">Go to Products</button>
<button on:click="set({ section: 'hr'})">Go to HR</button>
<button on:click="set({ section: 'verticals'})">Go to Verticals</button>
<div id="container">
<Slideshow bind:section></Slideshow>
<Slideshow bind:prevSection></Slideshow>
</div>
<style>/* Not important */</style>
<script>
export default {
onstate({ changed, current, previous }) {
if (changed.section && previous) {
this.set({prevSection: previous.section});
}
},
oncreate() {},
onupdate() {},
ondestroy() {},
components: {
Slideshow: '../components/Slideshow.html'
},
data() {
return {
section : 'products',
prevSection : ''
};
}
}
</script>
我想要一个初始状态,其中 section=products 且 prevSection 为空,然后每次单击按钮时,prevSection 获取 section 的值,然后 section 更新为由按钮。
非常感谢您的帮助!
不确定这是否是您要查找的内容,但我能够通过将逻辑从 onstate 移动到 onupdate
在您的示例中正确更新 section 和 prevSection 变量原来问题不在于代码本身,而是
<Slideshow bind:prevSection></Slideshow>
显然正在接收 prevSection 道具,但我试图 console.log() section 属性。所以代码有点工作,我只是检查了错误的道具。
感谢所有花时间回答甚至只是看一下的人!