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?
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.
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...
Not the issue here too, but i got the same thing when i wrote by mistake two mounted functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With