Vue.js – Cannot read property ‘get’ of undefined

Trying to get a http request in Vue.js:

this.$http.get('ApiURL')

I got error: Cannot read property ‘get’ of undefined

After a long, long searching I found the solution.

In your main.js file bold lines are the solution:

//your imports...
import vueResource from 'vue-resource'

Vue.use(vueResource)

new Vue({
  //your vue configuration
})

And then you can use Vue.http in your methods:

methods: {
  yourMethod: function () {
    Vue.http.get('yourApiURL').then((response) => {
        console.log('data: ', response.body)
        this.yourDataObject = response.body
    })
  }
}

You are welcome!

Advertisements

A perfect web app framework

What should a perfect web app framework do? I have programmed a few PHP and JavaScript applications and in almost every app I needed:

  • Routes
  • Built in support for LESS/SASS (or at least simple installation)
  • Built in jQuery
  • ORM or simple Model-database access. Mainly for relations – 1:m, n:m
  • AJAX support. I mean auto redraw template after successful AJAX call or/and websockets support for realtime web
  • Internationalization and localization support
  • easy deployment (eg. $ meteor deploy myapp.meteor.com)
  • Pre-built authentication
  • tools for CSS and JS minification
  • mapping data from/to HTML form

MeteorJS is closest to be the perfect web app framework. I hope and believe it will be the perfect web app framework.

“clone” file input

I had a form with plenty of inputs and one (hidden) file input. File had to be selected in modal window. So I cloned the file input in modal into the form. It worked prefectly for Firefox and Opera but not for Chrome for security reasons.

I have read plenty of similar solutions but none of them worked in Chrome.

So I found out other way – move the file input instead of cloning.
See http://jsfiddle.net/E8DBZ/2/

JavaScript function with default values

In PHP you can define default values like this:

function add($a = 0, $b = 0) {
  return $a + $b;
}

So I did the same in JavaScript:

function add(a = 0, b = 0) {
  return a + b;
}

But it works only in Firefox. Other browsers do not support this format.
Cross browser default values should be defined like this:

function add(a, b) {
  a = a || 0;
  b = b || ;
  return a + b;
}

Select2 placeholder does not work (solution)

I was frustrated by select2 plugin. I did not understand why on plugin’s homepage placeholder works and on my site doesn’t. I tried to google it and i found that you must add <option></option> for your select. I tried to add multiple options with value but placeholder did not work. The first option must be empty in order to get placeholder working!
Like this:

<select id="sel" placeholder="Hello">
  <option></option>
  <option>Option value</option>
</select>

<script type="text/javascript">
  $("#sel").select2();
</script>

Here is working example: http://hromnik.com/web/select2/
Check source code for details.