问题描述

vue.esm.js?71e4:479 [Vue warn]: Error in created hook: "ReferenceError: $http is not defined"

found in

---> <MainSection> at D:\vue\Cnodejs\test\VueCnodeJs\src\components\MainSec.vue
       <App> at D:\vue\Cnodejs\test\VueCnodeJs\src\App.vue
         <Root>

vue.esm.js?71e4:566 ReferenceError: $http is not defined
    at VueComponent.created (MainSec.vue?9425:20)
    at callHook (vue.esm.js?71e4:2665)
    at VueComponent.Vue._init (vue.esm.js?71e4:4226)
    at new VueComponent (vue.esm.js?71e4:4396)
    at createComponentInstanceForVnode (vue.esm.js?71e4:3678)
    at init (vue.esm.js?71e4:3495)
    at createComponent (vue.esm.js?71e4:5147)
    at createElm (vue.esm.js?71e4:5090)
    at createChildren (vue.esm.js?71e4:5218)
    at createElm (vue.esm.js?71e4:5123)

代码

MainSec.vue

<template>
  <div class="secDiv">
    <div v-for="item of content">
    <p>{{item}}</p>

    </div>
  </div>
</template>

<script>
export default {
  name: 'MainSection',
  data () {
    return {
      content: [],
    }
  },
  created(){
    this.$http({
      url: 'https://cnodejs.org/api/v1/topics',
      method: 'get',
      params: {
        page: 1,
        limit: 10,
        mdrender: 'false',
      },
    }).then((res) => {
      this.content = res.body.data;
      console.log(this.content);
    }).catch((res) => {
      console.log('MaiSec.vue: ', res);
    });
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.secDiv{
  width: 60%;
  height: 40rem;
  background: #fff;
  border: 1px solid #ddd;
}
  p{
    color: red;
  }
</style>

App.vue

<template>
  <div id="app">
    <main-sec></main-sec>
    <side-sec></side-sec>
  </div>
</template>

<script>
  import mainSec from './components/MainSec';
  import sideSec from './components/SideSec';

  export default {
    name: 'app',
    components: {
      mainSec,
      sideSec
    }
  };
</script>

<style scoped>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
    display: flex;
    justify-content: space-around;
  }
</style>

原因

main.js中没有引入vueresource包,或者npm没有安装该包
首先检查是否安装vueresource包,然后在main.js中添加引入。

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import VueResource from 'vue-resource'

Vue.use(VueResource);
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
});
Logo

前往低代码交流专区

更多推荐