Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  106] [ 2]  / answers: 1 / hits: 17992  / 7 Years ago, tue, september 26, 2017, 12:00:00

I would like to load some data with vue-resource when a page loads, then re-load that data if a refresh button is pressed.



To keep my code DRY I wanted to put this functionality in a method. This was my first attempt:



index.html:



<div id=app></div>


app.js:



const Vue = window.Vue = require(vue);
require(vue-resource);
const App = require(./components/App.vue);

window.app = new Vue({
el: #app,
render: h => h(App)
});


components/app.vue:



<template>
<div>
<h1>Test</h1>
<p>{text}</p>
<button @click=loadData>Reload</button>
</div>
</template>
<script>
export default {
// This fails
mounted: this.loadData,
methods: {
loadData() {
// This syntax may be wrong, too. But the function isn't
// even running, so I haven't started to debug this yet
this.$http.get(https://icanhazip.com)
.then(xhr => this.text = xhr.body);
}
}
};
</script>


This throws an error on line 10 of components/app.vue:



    mounted: this.loadData,


Saying Uncaught TypeError: Cannot read property 'reloadData' of undefined



How can I get the mounted function to refer to any of the methods defined in methods?


More From » vue.js

 Answers
55

You should use mounted event in following way with correct method declaration.


export default {        
mounted() {
this.loadData();
},
methods: {
loadData() {
// This syntax may be wrong, too. But the function isn't
// even running, so I haven't started to debug this yet
this.$http.get("https://icanhazip.com")
.then(xhr => this.text = xhr.body);
}
}
};

More details can be found here.

https://v2.vuejs.org/v2/api/#mounted


[#56379] Saturday, September 23, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haylie

Total Points: 26
Total Questions: 108
Total Answers: 104

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
;