vue.js - vue引入vue-resource无法使用$http.get

查看:1223
本文介绍了vue.js - vue引入vue-resource无法使用$http.get的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我按照教程使用vue-cli新建项目
npm install -g vue-cli
vue init webpack my-project
然后又npm install vue-resource --save-dev
在某个vue文件中想调用vue-resource,但是控制台报错了
Uncaught TypeError: Cannot read property 'get' of undefined
Demo.vue

const Vue = require('vue');
const VueResource = require('vue-resource');
// Don't forget to call this
Vue.use(VueResource);
const resource = new VueResource();
export default {
  data() {
    return {
      news: [
        { title: 'Learn JavaScript' },
        { title: 'Learn Vue.js' },
        { title: 'Build Something Awesome' },
      ],
    };
  },
  ready: () => {
    // 改成resource.$http.get也不行
    console.log(this.$http);
    this.$http.get('http://news-at.zhihu.com/api/4/news/latest', data => {
      this.$set('news', data.stories);
    });
  },
};

解决方案

谢谢,改过后报了,该怎么调用呢
TypeError: Cannot read property '$http' of undefined
main.js是

import Vue from 'vue';
import App from './App';
import VueResource from 'vue-resource';
Vue.use(VueResource);

/* eslint-disable no-new */
new Vue({
  el: 'body',
  components: { App },
});

调用代码是

<template>
  <h1>this is Stories list</h1>
  <div class="newsList">
    <ul>
      <li v-for="item in news"> {{ item.title }} </li>
    </ul>
  </div>

</template>

<script>

export default {
  data() {
    return {
      news: [
        { title: 'Learn JavaScript' },
        { title: 'Learn Vue.js' },
        { title: 'Build Something Awesome' },
      ],
    };
  },
  ready: () => {
    this.$http.get('http://news-at.zhihu.com/api/4/news/latest', data => {
      this.$set('news', data.stories);
    });
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
a {
    color: #4298ba;
    text-decoration: none;
}
</style>

知道原因了,把

ready: () => {
    this.$http.get('http://news-at.zhihu.com/api/4/news/latest', data => {
      this.$set('news', data.stories);
    });
  },

改为

  ready() {
    this.$http.get('http://news-at.zhihu.com/api/4/news/latest', data => {
      this.$set('news', data.stories);
    });
  },

就可以了。

这篇关于vue.js - vue引入vue-resource无法使用$http.get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆