Search code examples
vue.jscomponents

Switching out components in vue on a click event


I am making a website that has a storytelling purpose. When the user clicks on something, a new layout will be presented, either a video that covers the whole screen or a picture. When the button next is pressed it has to show something new but the url has to stay the same.

I have been trying to work with components in vue, but I don't understand how to handle clicks to rewrite the page to something else.

I have a file start.vue with a template in it for start screen and also firstvideo.vue (for example) with its own template. How do I connect these two with a click event?

App.vue-file:

<template>
        <div id="app">
            <keep-alive>
                <component :is="selectedComponent"></component>
            </keep-alive>
        </div>
</template>

<script>
    import Start from './components/Start.vue'
    import FlyingVideo from './components/FlyingVideo.vue'

    export default {
        name: 'app',
        components: {
            Start, FlyingVideo
        },
        data (){
            return {
                selectedComponent: 'Start'
            }
        }
    };
</script>

Start.vue-file:

<template>
    <span>
        <h1>Title</h1>
        <button @click="selectedComponent = 'FlyingVideo'">Start</button>
    </span>
</template>

<script>
    export default {
        name: 'Start'
    }
</script>

FlyingVideo.vue-file:

<template>
    <span>
        <h1>Video</h1>
        <p>Video coming soon</p>
    </span>
</template>

<script>
    export default {
        name: 'FlyingVideo'
    }
</script>

From the code that I have written i get to display the first component from Start.vue but I can't click and display the video.


Solution

  • You can do without the view router. In your App.js component you will initialize all your components, and display them or not according to your state. It would be better to use vuex to manage your store in this case.

    So you can do something like this

    <component1 v-if="toDisplayComponent1"></component1>
    <component2 v-if="toDisplayComponent2"></component2>
    ...
    

    And into your component use the $store to mutate toDisplayComponent1 ...