我很难理解vue.js.我目前正试图弄清楚如何获取或调用API。我设法设置了index.html
app.js
,也可以设置node_modules
中包含的软件包。
当我尝试运行我的文件时,我在我的控制台上获得TypeError: Cannot read property 'get' of undefined
。它说我需要安装vue-resource并在下面添加两行代码。
我在哪里准确插入它们?它在我的app.js里面吗?对不起我的无知,但我还是Javascript和Vue.js的新手
var Vue = require('vue');
Vue.use(require('vue-resource'));
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script src="https://unpkg.com/vue" ></script>
<title>article-app</title>
</head>
<body>
<div id="vue-app">
{{ articles }}
</div>
<script src="app.js"></script>
<script src="main.js" ></script>
</body>
</html>
var article = new Vue({
el: '#vue-app',
data: {
articles: ''
},
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
var that = this
this.$http.get('http://localhost/aim-beta/rest/export/json/article'),
function (data) {
this.articles = data.main.temp;
}
}
}
});
答案 0 :(得分:0)
在名为vue-resource
plugins/vue-resource.js
const Vue = require('vue');
const Resource = require('vue-resource');
Vue.use(Resource);
然后需要app.js
中的文件,如下所示:
require('./plugins/vue-resource.js');
new Vue({
el: '#vue-app',
data: {
articles: ''
},
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
this
.$http
.get('http://localhost/aim-beta/rest/export/json/article',
function (data) {
this.articles = data.main.temp;
})
}
}
});
因此,您的新文件夹结构将如此:
- index.html
- app.js
+ plugins
- vue-resource.js
使用原生JavaScript Fetch API
// You don't need vue resources!!!
// require('./plugins/vue-resource.js');
// Read more about Fetch API: [https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch][1]
new Vue({
el: '#vue-app',
data: {
articles: ''
},
created: function () {
this.fetchData();
},
methods: {
fetchData: function () {
fetch('http://localhost/aim-beta/rest/export/json/article', {
method: 'GET'
}).then(function(data) {
console.log(data);
this.articles = data.main.temp;
})
}
}
});