Adding XHR to Vue JS webpack

I am trying to add XHR to Vue. I am getting XHR not defined error. I followed the XHR instructions installed with NPM and added it to the webpack.base file under an alias. I call it inside the Hello.vue file template file that comes with the vue-cli boiler plate. I am using "npm run dev", do I need to rebuild somehow?

resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
  'vue$': 'vue/dist/vue.esm.js',
  '@': resolve('src'),
  'request$': 'xhr'
}

      

},

From Hello.vue inside a tag

xhr({
uri: "http://localhost:8081/service",
headers: {
    "Content-Type": "application/json"
}

}, function (err, resp, body) {
    list = resp;
})

      

Code in Hello.vue

    <script>
var xhr = require("xhr")

var spells = [];

function doGetSpells(){

        //var self = this;
        xhr({
          uri: "http://localhost:8081/spellNames",
          headers: {
              "Content-Type": "application/json"
          }
      }, function (err, resp, body) {              
          spells = JSON.parse(body);
          console.log(spells);
      })           
}

export default {
  name: 'sideBar',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      spellList: spells   
    }
  },
  methods: {
    getSpells(){
      doGetSpells();
    },
    mounted () {
      doGetSpells();
    }
  }

}
</script>

      

+3


source to share


1 answer


var xhr = require("xhr")

xhr.get('/post-to-me', function(err, resp) {
   // callback
})

      

You must pass a callback function as parameters, it will be called when the action is done.



In your callback, you will access the Vue instance using "this":

this.spellList = []

      

+1


source







All Articles