Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  131] [ 1]  / answers: 1 / hits: 20885  / 6 Years ago, fri, june 29, 2018, 12:00:00

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?


More From » vue.js

 Answers
25

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.


[#54090] Monday, June 25, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luna

Total Points: 698
Total Questions: 114
Total Answers: 93

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
luna questions
;