【问题标题】:Updating data from onstate() in Svelte从 Svelte 中的 onstate() 更新数据
【发布时间】:2019-09-07 02:49:31
【问题描述】:

我刚开始使用 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 更新为按钮指定的新值。

非常感谢您的帮助!

【问题讨论】:

  • 离题但如果你刚刚开始使用 svelte,请务必查看 v3,它比 v2 有了巨大的改进。 Portal

标签: svelte


【解决方案1】:

不确定这是否是您要查找的内容,但通过将逻辑从 onstate 移动到 onupdate,我能够在您的示例中正确更新 section 和 prevSection 变量

【讨论】:

    【解决方案2】:

    原来问题不在于代码本身,而在于

    <Slideshow bind:prevSection></Slideshow>
    

    显然正在接收 prevSection 道具,但我试图 console.log() section 属性。所以代码有点工作,我只是检查了错误的道具。

    感谢任何花时间回答甚至只是看看它的人!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2019-09-21
      • 2020-03-16
      • 2021-10-04
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多