Closed cnweibo closed 8 years ago
Hi,
you may refer to a similar question I made some days ago: https://github.com/vuejs/vue-async-data/issues/22
Anyway if you really need it, I think it'd pretty simple to take the source code and adapt it to the 2.x lifecycle
Hi, @dwightjack i have no knowledge about how to write vuejs plugin. In that ticket, you mention to use vue-router for vue-async-data fetching, but i do not like to use vue-router in simple application, so, can you make this plugin work with vuejs2.0 on next branch or tell more information on how to do it myself? thanks~!
Hi @cnweibo,
you don't need vue-router
at all. My mention was related to this line which sets a watcher on the $route
property. $route
is added by vue-router and identifies the current route.
That watcher is needed because if you set a Post
component to display a single post (ie: /posts/10
), that component will still be reused if you jump to another single post URL (ie: /posts/11
) using something like a next / previuos post link. Since the Post
component is the same, the created
hook won't be called again and the new data won't be fetched.
Right now I cannot build something enough solid to be packaged as a replacement for this plugin, but if you're not using vue-router
you could just implement a custom mixin like this:
var asyncData = {
created: function () {
var self = this;
var resolve = function (data) {
if (data) {
for (var key in data) {
self[key] = data[key];
}
}
self.loading = false;
};
var reject = function (reason) {
var msg = '[vue] async data load failed'
if (reason instanceof Error) {
console.warn(msg)
throw reason
} else {
console.warn(msg + ': ' + reason)
}
};
self.loading = true;
var res = this.fetchData.call(this, resolve, reject)
if (res && typeof res.then === 'function') {
res.then(resolve, reject)
}
}
}
//usage with jQuery.getJSON
var MyComponent = {
mixins: [asyncData],
data: function () {
return {
//remember to set `loading` as a component data, so it will change when loading starts / finishes
loading: false,
posts: []
}
},
methods: {
fetchData: function () {
return jQuery.getJSON('/api/posts/').then(function (posts) {
return {
posts: posts
};
})
}
}
}
I've not tested it, but should work :)
@dwightjack , thanks for your great code, it seems what i expected. I will test in my project. Thanks again!
Hi, Do you have plan to make this vue-async-data work with vuejs2.0? Thanks~!