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);
    });
  },

就可以了。

回答:

下面这些应该放在入口文件main.js里, 而不是组件文件里

const Vue = require('vue');
const VueResource = require('vue-resource');
Vue.use(VueResource);

暂无评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注