2017-03-26 89 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 = []