mintedsky
mintedsky

Reputation: 1103

How to export an named instance in Vue.js, stop using: var app = this

I'm using .vue templates within a vue-cli created webpack project.

I typically use "export default" to export files, like this:

 export default {
   data () {
     return {
       message:''
     };
 },
 ...

Later in the script, when I try to access the instance, it seems within any function or third party library like axios, I have to write something like this at the top:

 var app = this;

so I can access data properties...for example:

    var app = this;

    axios.post('https://test.com/api/getMessage',{}).then(res => {
        app.message = res.data.message
    })
    .catch(error => {
        console.log(error)
    });

But calling var app = this; all the time gets really tiresome.

I would prefer to put the instance in a variable like:

 let app = {
  data () {
    return {
       message:''
  };
 },
 methods :{
   getMessage:function(){

        axios.post('https://test.com/api/getMessage',{}).then(res => {
            app.message = res.data.message
        })
        .catch(error => {
            console.log(error)
        });
   } 
 }  
}

But I don't understand how to export or import it properly. It seems every example just uses export default. So to restate my question, is there better /smarter way to export and import the script so I don't have to write:

 var app = this; 

Upvotes: 0

Views: 348

Answers (1)

Jeff
Jeff

Reputation: 25211

axios.post('https://test.com/api/getMessage',{}).then(res => {
    this.message = res.data.message
})

That should work - Arrow functions take place in the scope in which they are written, meaning this will refer to your Vue instance there. If you were not using arrow functions, you would have to specifically bind the scope:

axios.post('https://test.com/api/getMessage',{}).then(function(res){
    this.message = res.data.message
}.bind(this))

Upvotes: 2

Related Questions