Search code examples
javascriptvue.jsvue-component

How call a method from an other component


I have made an example in Codesandbox

Is there a way to collapse the sidebar by clicking on the button 'Col-2'. The button 'Col-1' is working fine, but it's necessary that is works by clicking on 'Col-2'.

I've tried to call the collapsedButton but this didn't work.

<script>
    export default {
        name: 'template',
        methods: {
            setCollapsed () {
                this.collapsed = !this.collapsed
            },
             collapseButton () {
                this.$emit('setCollapsed')
                this.collapsed = !this.collapsed
            }
        }
    }
</script>

Can someone help me out with this?


Solution

  • The recommended way to achieve this is to use a store.

    The store is a module, external to any component, which can be imported in any number of components. When the state of the store (which is pretty much like the data function of a component) is changed, the change is propagated in every single component where the store is used.


    Since you're using Vue 2, you could use a mixin.

    Here's a mixin using a basic version of a store, under the hood: https://codesandbox.io/s/vue-forked-tz1yox?file=/src/components/sidebar.vue

    In more detail, it uses a reactive object which serves as shared state for sidebar's collapsed status while exposing a writable computed (collapsed) and a toggleSidebar method.

    Using the mixin in any component is the equivalent of writing the writable computed and the method into the component.

    Note: mixins don't play nice with TypeScript. But the above solution doesn't need a mixin. I only used one so I didn't have to write the same computed and same method in both components.
    The key to it working is the shared/external reactive object. In Vue 3 you would achieve this using Composition API.