2017-03-26 90 views
3

我正在尝试将XHR添加到Vue。我得到错误XHR没有定义。我遵循随NPM一起安装的XHR指令,将其添加到别名下的webpack.base文件中。我在vue-cli锅炉板附带的模板文件Hello.vue文件中调用它。我使用“npm run dev”,我需要重建吗?向Vue JS webpack添加XHR

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

},

从Hello.vue,在标签内

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

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

守则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> 
+0

你能证明你在Hello.vue使用的代码? – Jewel

+0

我将它添加到原始帖子中。 – Jason

+1

您是否在Hello.vue中添加了'var xhr = require(“xhr”)''。你能显示完整的hello.vue吗? – Jewel

回答

1
var xhr = require("xhr") 

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

你应该通过一个回调函数作为参数,它会在行动时被调用已经完成了。

在回调中,您将使用访问您的Vue实例“这个”:

this.spellList = []