J
J
JohnDaniels2017-01-18 18:39:28
JavaScript
JohnDaniels, 2017-01-18 18:39:28

How to change data in vue.js component?

There are two components - a button and a menu that should be opened by this button.

button:

<template>
       <button type="button" class="navbar-toggle collapsed" @click="showLeftMenu">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
</template>

<script type="text/babel">
    export default{
        methods:{
            showLeftMenu(){
                this.$root.$emit('show')
            }
        }
    }
</script>


menu:
<template>
    <div class="sidemenu"  v-show="visible">
        {{visible}}
    </div>
</template>

<script type="text/babel">
    export default{
        data(){
            return{
                visible:  false
            }
        },
        created: function(){
           console.log(this.visible)
        },
        mounted(){
            this.$root.$on('show', function () {
                console.log('open!')
                this.visible = true;
                console.log(this.visible)
            })
        }
    }
</script>


a button click is caught in the menu, true is displayed in the console, but v-show does not work

be6f1140003c44ba8600872ec84a79b9.png

on the page, nothing changes,
07ad8f9179d04d6ba3a8c4f885c71238.png

what did I miss?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2017-01-18
@JohnDaniels

Because in the callback function your context is most likely wrong.

mounted(){
            var vm = this;
            this.$root.$on('show', function () {
                console.log('open!')
                vm.visible = true;
                console.log(vm)
            })
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question