j0zeft
j0zeft

Reputation: 649

Vue mounted event not executing

I'm trying to build a page where a variable should be set as soon as the page is loaded. I placed my method and tried debugging it repeatedly with no result at all, then I tried to just print a string to the console at mounted and nothing happened either... I'm not sure if I'm missing something.

I scaffold my project using Vue CLI and at the moment, in the following code, I'm going to insert changes to the HelloWorld.vue from the template

I have added a button as a check as well,

<button onclick="foo">foo</button>

the script section of the page looks like this:

<script>
    export default {
        el: '#app',
        data: {
            message: 'Hello Vue.js!'
        },
        methods: {
            mounted: function() {
                console.log("Mounted!")
            },
            foo: function() {
                console.log("button")
            }
        }
    }
</script>

expected behaviour is to get "Mounted!" on the console upon save and refresh, and "button" whenever I click the button. I get nothing when the page is displayed, and only "button" appears whenever I click the button. Is mounted the wrong function to use here or am I missing something else?

Upvotes: 7

Views: 25037

Answers (3)

Apix Raser
Apix Raser

Reputation: 23

Not the issue here too, but i got the same thing when i wrote by mistake two mounted functions.

Upvotes: 2

Ankit Kumar Ojha
Ankit Kumar Ojha

Reputation: 2384

Ah. It's a simple and common mistake people do. Here is how you should actually write mounted.

<script>
    export default {
        el: '#app',
        data: {
            message: 'Hello Vue.js!'
        },
        methods: {
            foo: function() {
                console.log("button")
            }
        },
        mounted: function() {
            console.log("Mounted!")
        },
    }
</script>

mounted should be at the same level with methods, data or computed. Not inside methods.

That's all, it should work now.

I hope it helps.

Upvotes: 35

Leo
Leo

Reputation: 1619

Not the issue here, but I experienced the same thing when I forgot to include the closing </script> tag. Just in case it saves someone else a bit of head scratching...

Upvotes: 6

Related Questions