Updating data from onstate() in Svelte

时间:2019-04-16 22:57:52

标签: svelte

I just got started with Svelte/Sapper and there's this silly thing I'm not getting. Maybe it's because I'm used to Vue and I'm not understanding Svelte's paradigm.

I'm basically making a slider or carousel. For that I need to know what is the current section to be shown (which will help determine the entry animation) and keep on record the previous section (just for as long as it needs to transition out).

I'm guessing I can have a

<button on:click="set({ section: 'products'})">Go to Products</button>

to switch sections, and this works fine. But then I want to have a detection in onstate() so that when the section is changed, the prop prevSection gets updated as well.

Here's the (relevant) code I have so far :

<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>

I'd like to have an initial state where section=products and prevSection is empty, and then every time I click a button, prevSection takes the values of section, and then section updates to the new value dictated by the button.

Thanks so much for your help !

2 个答案:

答案 0 :(得分:0)

不确定这是否是您要查找的内容,但是通过将逻辑从onstate转换为onupdate,我能够在您的示例中正确获取section和prevSection变量

答案 1 :(得分:0)

所以事实证明问题不在于代码本身,而是

<Slideshow bind:prevSection></Slideshow>

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

感谢所有花时间回答甚至只是看一看的人!