Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
j0zeft Avatar asked Jun 29 '18 15:06

j0zeft


3 Answers

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.

like image 53
Ankit Kumar Ojha Avatar answered Nov 09 '22 05:11

Ankit Kumar Ojha


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...

like image 4
Leo Avatar answered Nov 09 '22 04:11

Leo


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

like image 2
Apix Raser Avatar answered Nov 09 '22 05:11

Apix Raser