Reputation: 4750
I have a Vue instance called appDetails. This instance belongs to app.html. In it I declared function getApp, which returns the name of app:
var appDetails = new Vue({
el: '#appDetails',
methods: {
getApp() {
var path = url;
var formData = "id=" + id;
return axios.get(path, formData)
.then((res) => {
return res.data.name;
})
}})
Then in another js file I created product instance. This js file belongs to product.html. In it I declared computed property. In body of property I want to call a function of appDetails Vue instance. The returned data of the property is the name of app.
var product = new Vue({
el: '#product',
computed : {
app_name: function() {
appDetails.getApp()
.then((returnVal) => {
return returnVal;
})
}});
In product.html I wrote:
<a>{{app_name}}</a>
But when I load page, there is no text. tag is empty.
But when I tried to console log it showed me a name. Anybody knows how to solve this problem?
Upvotes: 0
Views: 108
Reputation: 64634
app_name
resolves to undefined
because the function does not return anything. Computed properties cannot be asynchronous, so instead you should create a data field on your component and call an asynchronous function that populates it. If you only need to fetch the data once, then mounted
is probably a good place to do this.
var product = new Vue({
el: '#product',
data: function () {
return {
app_name: ''
}
},
mounted: function () {
appDetails.getApp()
.then((returnVal) => {
this.app_name = returnVal;
})
}
});
Also, does getApp()
depend at all on the state of the AppDetails component? If not, it may make sense to keep it as a standalone function as it would be easier to use import it into both components.
Upvotes: 1