[Vuejs]-Problem when triggering a Vue function to change some component field

1👍

OK, So, I’m posting myself the answer.

What @AlexBrohshtut spotted was right. Fat-arrow functions were an issue.

However, the most important part is that I hadn’t put my function in methods (I had them in data section too). Pff…

So, this works:

<html>
    <head>
        <link rel="stylesheet" href="index.css">
        <script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>
    </head>
    <body>

        <div id="app">
            {{ message }}
            This is another thing: <b>{{thing}}</b><br>
            <span :title="title" @click="doSomething">NO TITLE</span>
            <ul v-for="item in items">
                <li>{{item}}</li>
            </ul>
            <button @click="buttonClicked">{{toggleMessage}}</button>
            <label v-if="labelVisible">This is my label</label>
        </div>
    </body>
    <script>
        var app = new Vue({ 
            el: '#app',
            data: {
                message: 'Hello Vue!',
                thing: 'thing',
                title: "This is the title",
                doSomething: ()=>{
                    alert("did something")
                },
                items: ["one", "two", "three"],
                labelVisible: true,
                toggleMessage: "Hide Label",

            },
            methods: {
                buttonClicked: function() {
                    console.log("button");
                    this.labelVisible = !this.labelVisible;
                    console.log(this.labelVisible);
                    if (this.labelVisible) {
                        this.toggleMessage = "Hide Label";
                    }
                    else {
                        this.toggleMessage = "Show Label";
                    }
                    console.log(this.toggleMessage);
                }
            }
        });
    </script>
</html>

Leave a comment