I have a resource.js which is an ES6 class exported :
import Vue from 'vue'
import VueResource from 'vue-resource'
Vue.use(VueResource)
export class Resource {
getMovies () {
// GET /someUrl
return Vue.http.get('http://localhost:3335/cardname').then((response) => {
console.log('success')
return response
}, (response) => {
console.log('problem')
return response
})
}
}
Then I am importing it in my component and passing the data in the in view/component:
<script>
import { movies } from '../mock'
import { Resource } from '../services/resource'
const resourceService = new Resource()
export default {
name: 'hello',
data () {
return {
msg: 'MovieRama',
count: 0,
movies: movies.movies,
totalMovies: movies.total,
test: null
}
},
mounted: function () {
// Note this part
let that = this
resourceService.getMovies().then(function (result) {
that.test = result
})
},
methods: {
boom: function () {
console.log('Woho')
},
updateCount: function () {
this.count++
}
}
}
</script>
Please note the mounted
method. Why do I need to keep the scope like that in order to pass data in data () { } ?
I am looking at the vue.js documentation and that doesn't seem necessary:
http://vuejs.org/guide/instance.html#Instance-Lifecycle-Hooks
Since you used an anonymous function, it has its' own scope when you call this
. If you use an arrow function you can get rid of that
resourceService.getMovies().then((result) => {
this.test = result
})
I also recommend looking at the docs for creating resources: https://github.com/vuejs/vue-resource/blob/master/docs/resource.md
This is a way to create a class that automatically has methods for get
, update
, delete
, etc.